I have an enum class that stores 4 seasons and would like to be able to move to the next season. When I get to the end (FALL), I want it to go back to the first one (WINTER). Is there a simple way of doing this or am I better off just using a list or some other structure. Some answers I've found online seem like overkill so I'm curious if using an enum is even worth it.
from enum import Enum, auto
class Season(Enum):
WINTER = auto()
SPRING = auto()
SUMMER = auto()
FALL = auto()
>>> season = Season.SUMMER
>>> season.next()
<Season.FALL: 4>
>>> season.next()
<Season.WINTER: 1>
Since Enum
already supports the iteration protocol, that is very easy, using itertools.cycle
:
>>> from itertools import cycle
>>> seasons = cycle(Season)
>>> next(seasons)
<Season.WINTER: 1>
>>> next(seasons)
<Season.SPRING: 2>
>>> next(seasons)
<Season.SUMMER: 3>
>>> next(seasons)
<Season.FALL: 4>
>>> next(seasons)
<Season.WINTER: 1>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With