Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple method for circularly iterating over an enum?

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>
like image 588
Rhombus Avatar asked Sep 06 '25 03:09

Rhombus


1 Answers

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>
like image 121
mkrieger1 Avatar answered Sep 07 '25 20:09

mkrieger1