Get the next constant / property counter

Suppose I have a counter, is it possible to get the following property? So, if I had today=Days.Sunday , could I do something like tomorrow=today.next() ?

Example:

 class Days(Enum): Sunday = 'S' Monday = 'M' ... Saturday = 'Sa' 

I know that I could use tuples (for example, below) to do something like tomorrow=today[1] , but I was hoping there was something built or more elegant.

 class Days(Enum): Sunday = ('S','Monday') Monday = ('M','Tuesday') ... Saturday = ('Sa','Sunday') 
+7
python enums enumeration
source share
2 answers

That's right.

Just add the desired functionality to the Days class:

 class Days(Enum): Sunday = 'S' Monday = 'M' Tuesday = 'T' Wednesday = 'W' Thursday = 'Th' Friday = 'F' Saturday = 'Sa' def next(self): cls = self.__class__ members = list(cls) index = members.index(self) + 1 if index >= len(members): index = 0 return members[index] 

and used:

 today = Days.Wednesday print(today.next()) # Days.Thursday 
+7
source share

You can create a dictionary to search the next day as follows:

 In [10]: class Days(Enum): Sun = 'Su' Mon = 'M' Tue = 'Tu' Wed = 'W' Thu = 'Th' Fri = 'F' Sat = 'Sa' In [11]: days = list(Days) In [12]: nxt = dict((day, days[(i+1) % len(days)]) for i, day in enumerate(days)) 

Quick test:

 In [13]: nxt[Days.Tue] Out[13]: <Days.Wed: 'W'> In [14]: nxt[Days.Sat] Out[14]: <Days.Sun: 'Su'> 
+2
source share

All Articles