8.13.enum — Support for enumerations¶
New in version 3.4.
Source code:Lib/enum.py
An enumeration is a set of symbolic names (members) bound to unique,constant values. Within an enumeration, the members can be comparedby identity, and the enumeration itself can be iterated over.
8.13.1. Module Contents¶
This module defines two enumeration classes that can be used to define uniquesets of names and values:Enum andIntEnum. It also definesone decorator,unique().
- class
enum.Enum¶ Base class for creating enumerated constants. See sectionFunctional API for an alternate construction syntax.
enum.unique()¶Enum class decorator that ensures only one name is bound to any one value.
8.13.2. Creating an Enum¶
Enumerations are created using theclass syntax, which makes themeasy to read and write. An alternative creation method is described inFunctional API. To define an enumeration, subclassEnum asfollows:
>>>fromenumimportEnum>>>classColor(Enum):...red=1...green=2...blue=3...
Note
Nomenclature
- The class
Coloris anenumeration (orenum) - The attributes
Color.red,Color.green, etc., areenumeration members (orenum members). - The enum members havenames andvalues (the name of
Color.redisred, the value ofColor.blueis3, etc.)
Note
Even though we use theclass syntax to create Enums, Enumsare not normal Python classes. SeeHow are Enums different? formore details.
Enumeration members have human readable string representations:
>>>print(Color.red)Color.red
…while theirrepr has more information:
>>>print(repr(Color.red))<Color.red: 1>
Thetype of an enumeration member is the enumeration it belongs to:
>>>type(Color.red)<enum 'Color'>>>>isinstance(Color.green,Color)True>>>
Enum members also have a property that contains just their item name:
>>>print(Color.red.name)red
Enumerations support iteration, in definition order:
>>>classShake(Enum):...vanilla=7...chocolate=4...cookies=9...mint=3...>>>forshakeinShake:...print(shake)...Shake.vanillaShake.chocolateShake.cookiesShake.mint
Enumeration members are hashable, so they can be used in dictionaries and sets:
>>>apples={}>>>apples[Color.red]='red delicious'>>>apples[Color.green]='granny smith'>>>apples=={Color.red:'red delicious',Color.green:'granny smith'}True
8.13.3. Programmatic access to enumeration members and their attributes¶
Sometimes it’s useful to access members in enumerations programmatically (i.e.situations whereColor.red won’t do because the exact color is not knownat program-writing time).Enum allows such access:
>>>Color(1)<Color.red: 1>>>>Color(3)<Color.blue: 3>
If you want to access enum members byname, use item access:
>>>Color['red']<Color.red: 1>>>>Color['green']<Color.green: 2>
If you have an enum member and need itsname orvalue:
>>>member=Color.red>>>member.name'red'>>>member.value1
8.13.4. Duplicating enum members and values¶
Having two enum members with the same name is invalid:
>>>classShape(Enum):...square=2...square=3...Traceback (most recent call last):...TypeError:Attempted to reuse key: 'square'
However, two enum members are allowed to have the same value. Given two membersA and B with the same value (and A defined first), B is an alias to A. By-valuelookup of the value of A and B will return A. By-name lookup of B will alsoreturn A:
>>>classShape(Enum):...square=2...diamond=1...circle=3...alias_for_square=2...>>>Shape.square<Shape.square: 2>>>>Shape.alias_for_square<Shape.square: 2>>>>Shape(2)<Shape.square: 2>
Note
Attempting to create a member with the same name as an alreadydefined attribute (another member, a method, etc.) or attempting to createan attribute with the same name as a member is not allowed.
8.13.5. Ensuring unique enumeration values¶
By default, enumerations allow multiple names as aliases for the same value.When this behavior isn’t desired, the following decorator can be used toensure each value is used only once in the enumeration:
@enum.unique
Aclass decorator specifically for enumerations. It searches anenumeration’s__members__ gathering any aliases it finds; if any arefoundValueError is raised with the details:
>>>fromenumimportEnum,unique>>>@unique...classMistake(Enum):...one=1...two=2...three=3...four=3...Traceback (most recent call last):...ValueError:duplicate values found in <enum 'Mistake'>: four -> three
8.13.6. Iteration¶
Iterating over the members of an enum does not provide the aliases:
>>>list(Shape)[<Shape.square: 2>, <Shape.diamond: 1>, <Shape.circle: 3>]
The special attribute__members__ is an ordered dictionary mapping namesto members. It includes all names defined in the enumeration, including thealiases:
>>>forname,memberinShape.__members__.items():...name,member...('square', <Shape.square: 2>)('diamond', <Shape.diamond: 1>)('circle', <Shape.circle: 3>)('alias_for_square', <Shape.square: 2>)
The__members__ attribute can be used for detailed programmatic access tothe enumeration members. For example, finding all the aliases:
>>>[nameforname,memberinShape.__members__.items()ifmember.name!=name]['alias_for_square']
8.13.7. Comparisons¶
Enumeration members are compared by identity:
>>>Color.redisColor.redTrue>>>Color.redisColor.blueFalse>>>Color.redisnotColor.blueTrue
Ordered comparisons between enumeration values arenot supported. Enummembers are not integers (but seeIntEnum below):
>>>Color.red<Color.blueTraceback (most recent call last): File"<stdin>", line1, in<module>TypeError:unorderable types: Color() < Color()
Equality comparisons are defined though:
>>>Color.blue==Color.redFalse>>>Color.blue!=Color.redTrue>>>Color.blue==Color.blueTrue
Comparisons against non-enumeration values will always compare not equal(again,IntEnum was explicitly designed to behave differently, seebelow):
>>>Color.blue==2False
8.13.8. Allowed members and attributes of enumerations¶
The examples above use integers for enumeration values. Using integers isshort and handy (and provided by default by theFunctional API), but notstrictly enforced. In the vast majority of use-cases, one doesn’t care whatthe actual value of an enumeration is. But if the valueis important,enumerations can have arbitrary values.
Enumerations are Python classes, and can have methods and special methods asusual. If we have this enumeration:
>>>classMood(Enum):...funky=1...happy=3......defdescribe(self):...# self is the member here...returnself.name,self.value......def__str__(self):...return'my custom str!{0}'.format(self.value)......@classmethod...deffavorite_mood(cls):...# cls here is the enumeration...returncls.happy...
Then:
>>>Mood.favorite_mood()<Mood.happy: 3>>>>Mood.happy.describe()('happy', 3)>>>str(Mood.funky)'my custom str! 1'
The rules for what is allowed are as follows: names that start and end witha single underscore are reserved by enum and cannot be used; all otherattributes defined within an enumeration will become members of thisenumeration, with the exception of special methods (__str__(),__add__(), etc.) and descriptors (methods are also descriptors).
Note: if your enumeration defines__new__() and/or__init__() thenwhatever value(s) were given to the enum member will be passed into thosemethods. SeePlanet for an example.
8.13.9. Restricted subclassing of enumerations¶
Subclassing an enumeration is allowed only if the enumeration does not defineany members. So this is forbidden:
>>>classMoreColor(Color):...pink=17...Traceback (most recent call last):...TypeError:Cannot extend enumerations
But this is allowed:
>>>classFoo(Enum):...defsome_behavior(self):...pass...>>>classBar(Foo):...happy=1...sad=2...
Allowing subclassing of enums that define members would lead to a violation ofsome important invariants of types and instances. On the other hand, it makessense to allow sharing some common behavior between a group of enumerations.(SeeOrderedEnum for an example.)
8.13.10. Pickling¶
Enumerations can be pickled and unpickled:
>>>fromtest.test_enumimportFruit>>>frompickleimportdumps,loads>>>Fruit.tomatoisloads(dumps(Fruit.tomato))True
The usual restrictions for pickling apply: picklable enums must be defined inthe top level of a module, since unpickling requires them to be importablefrom that module.
Note
With pickle protocol version 4 it is possible to easily pickle enumsnested in other classes.
It is possible to modify how Enum members are pickled/unpickled by defining__reduce_ex__() in the enumeration class.
8.13.11. Functional API¶
TheEnum class is callable, providing the following functional API:
>>>Animal=Enum('Animal','ant bee cat dog')>>>Animal<enum 'Animal'>>>>Animal.ant<Animal.ant: 1>>>>Animal.ant.value1>>>list(Animal)[<Animal.ant: 1>, <Animal.bee: 2>, <Animal.cat: 3>, <Animal.dog: 4>]
The semantics of this API resemblenamedtuple. The firstargument of the call toEnum is the name of the enumeration.
The second argument is thesource of enumeration member names. It can be awhitespace-separated string of names, a sequence of names, a sequence of2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names tovalues. The last two options enable assigning arbitrary values toenumerations; the others auto-assign increasing integers starting with 1 (usethestart parameter to specify a different starting value). Anew class derived fromEnum is returned. In other words, the aboveassignment toAnimal is equivalent to:
>>>classAnimal(Enum):...ant=1...bee=2...cat=3...dog=4...
The reason for defaulting to1 as the starting number and not0 isthat0 isFalse in a boolean sense, but enum members all evaluatetoTrue.
Pickling enums created with the functional API can be tricky as frame stackimplementation details are used to try and figure out which module theenumeration is being created in (e.g. it will fail if you use a utilityfunction in separate module, and also may not work on IronPython or Jython).The solution is to specify the module name explicitly as follows:
>>>Animal=Enum('Animal','ant bee cat dog',module=__name__)
Warning
Ifmodule is not supplied, and Enum cannot determine what it is,the new Enum members will not be unpicklable; to keep errors closer tothe source, pickling will be disabled.
The new pickle protocol 4 also, in some circumstances, relies on__qualname__ being set to the location where pickle will be ableto find the class. For example, if the class was made available in classSomeData in the global scope:
>>>Animal=Enum('Animal','ant bee cat dog',qualname='SomeData.Animal')
The complete signature is:
Enum(value='NewEnumName',names=<...>,*,module='...',qualname='...',type=<mixed-inclass>,start=1)
| value: | What the new Enum class will record as its name. |
|---|---|
| names: | The Enum members. This can be a whitespace or comma separated string(values will start at 1 unless otherwise specified): 'red green blue'|'red,green,blue'|'red, green, blue' or an iterator of names: ['red','green','blue'] or an iterator of (name, value) pairs: [('cyan',4),('magenta',5),('yellow',6)] or a mapping: {'chartreuse':7,'sea_green':11,'rosemary':42} |
| module: | name of module where new Enum class can be found. |
| qualname: | where in module new Enum class can be found. |
| type: | type to mix in to new Enum class. |
| start: | number to start counting at if only names are passed in. |
Changed in version 3.5:Thestart parameter was added.
8.13.12. Derived Enumerations¶
8.13.12.1. IntEnum¶
A variation ofEnum is provided which is also a subclass ofint. Members of anIntEnum can be compared to integers;by extension, integer enumerations of different types can also be comparedto each other:
>>>fromenumimportIntEnum>>>classShape(IntEnum):...circle=1...square=2...>>>classRequest(IntEnum):...post=1...get=2...>>>Shape==1False>>>Shape.circle==1True>>>Shape.circle==Request.postTrue
However, they still can’t be compared to standardEnum enumerations:
>>>classShape(IntEnum):...circle=1...square=2...>>>classColor(Enum):...red=1...green=2...>>>Shape.circle==Color.redFalse
IntEnum values behave like integers in other ways you’d expect:
>>>int(Shape.circle)1>>>['a','b','c'][Shape.circle]'b'>>>[iforiinrange(Shape.square)][0, 1]
For the vast majority of code,Enum is strongly recommended,sinceIntEnum breaks some semantic promises of an enumeration (bybeing comparable to integers, and thus by transitivity to otherunrelated enumerations). It should be used only in special cases wherethere’s no other choice; for example, when integer constants arereplaced with enumerations and backwards compatibility is required with codethat still expects integers.
8.13.12.2. Others¶
WhileIntEnum is part of theenum module, it would be verysimple to implement independently:
classIntEnum(int,Enum):pass
This demonstrates how similar derived enumerations can be defined; for exampleaStrEnum that mixes instr instead ofint.
Some rules:
- When subclassing
Enum, mix-in types must appear beforeEnumitself in the sequence of bases, as in theIntEnumexample above. - While
Enumcan have members of any type, once you mix in anadditional type, all the members must have values of that type, e.g.intabove. This restriction does not apply to mix-ins which onlyadd methods and don’t specify another data type such asintorstr. - When another data type is mixed in, the
valueattribute isnot thesame as the enum member itself, although it is equivalent and will compareequal. - %-style formatting:%s and%r call the
Enumclass’s__str__()and__repr__()respectively; other codes (such as%i or%h for IntEnum) treat the enum member as its mixed-in type. str.format()(orformat()) will use the mixed-intype’s__format__(). If theEnumclass’sstr()orrepr()is desired, use the!s or!r format codes.
8.13.13. Interesting examples¶
WhileEnum andIntEnum are expected to cover the majority ofuse-cases, they cannot cover them all. Here are recipes for some differenttypes of enumerations that can be used directly, or as examples for creatingone’s own.
8.13.13.1. AutoNumber¶
Avoids having to specify the value for each enumeration member:
>>>classAutoNumber(Enum):...def__new__(cls):...value=len(cls.__members__)+1...obj=object.__new__(cls)...obj._value_=value...returnobj...>>>classColor(AutoNumber):...red=()...green=()...blue=()...>>>Color.green.value==2True
8.13.13.2. OrderedEnum¶
An ordered enumeration that is not based onIntEnum and so maintainsthe normalEnum invariants (such as not being comparable to otherenumerations):
>>>classOrderedEnum(Enum):...def__ge__(self,other):...ifself.__class__isother.__class__:...returnself.value>=other.value...returnNotImplemented...def__gt__(self,other):...ifself.__class__isother.__class__:...returnself.value>other.value...returnNotImplemented...def__le__(self,other):...ifself.__class__isother.__class__:...returnself.value<=other.value...returnNotImplemented...def__lt__(self,other):...ifself.__class__isother.__class__:...returnself.value<other.value...returnNotImplemented...>>>classGrade(OrderedEnum):...A=5...B=4...C=3...D=2...F=1...>>>Grade.C<Grade.ATrue
8.13.13.3. DuplicateFreeEnum¶
Raises an error if a duplicate member name is found instead of creating analias:
>>>classDuplicateFreeEnum(Enum):...def__init__(self,*args):...cls=self.__class__...ifany(self.value==e.valueforeincls):...a=self.name...e=cls(self.value).name...raiseValueError(..."aliases not allowed in DuplicateFreeEnum:%r -->%r"...%(a,e))...>>>classColor(DuplicateFreeEnum):...red=1...green=2...blue=3...grene=2...Traceback (most recent call last):...ValueError:aliases not allowed in DuplicateFreeEnum: 'grene' --> 'green'
Note
This is a useful example for subclassing Enum to add or change otherbehaviors as well as disallowing aliases. If the only desired change isdisallowing aliases, theunique() decorator can be used instead.
8.13.13.4. Planet¶
If__new__() or__init__() is defined the value of the enum memberwill be passed to those methods:
>>>classPlanet(Enum):...MERCURY=(3.303e+23,2.4397e6)...VENUS=(4.869e+24,6.0518e6)...EARTH=(5.976e+24,6.37814e6)...MARS=(6.421e+23,3.3972e6)...JUPITER=(1.9e+27,7.1492e7)...SATURN=(5.688e+26,6.0268e7)...URANUS=(8.686e+25,2.5559e7)...NEPTUNE=(1.024e+26,2.4746e7)...def__init__(self,mass,radius):...self.mass=mass# in kilograms...self.radius=radius# in meters...@property...defsurface_gravity(self):...# universal gravitational constant (m3 kg-1 s-2)...G=6.67300E-11...returnG*self.mass/(self.radius*self.radius)...>>>Planet.EARTH.value(5.976e+24, 6378140.0)>>>Planet.EARTH.surface_gravity9.802652743337129
8.13.14. How are Enums different?¶
Enums have a custom metaclass that affects many aspects of both derived Enumclasses and their instances (members).
8.13.14.1. Enum Classes¶
TheEnumMeta metaclass is responsible for providing the__contains__(),__dir__(),__iter__() and other methods thatallow one to do things with anEnum class that fail on a typicalclass, such aslist(Color) orsome_var in Color.EnumMeta isresponsible for ensuring that various other methods on the finalEnumclass are correct (such as__new__(),__getnewargs__(),__str__() and__repr__()).
8.13.14.2. Enum Members (aka instances)¶
The most interesting thing about Enum members is that they are singletons.EnumMeta creates them all while it is creating theEnumclass itself, and then puts a custom__new__() in place to ensurethat no new ones are ever instantiated by returning only the existingmember instances.
8.13.14.3. Finer Points¶
Enum members are instances of anEnum class, and eventhough they are accessible asEnumClass.member, they should not be accesseddirectly from the member as that lookup may fail or, worse, return somethingbesides theEnum member you looking for:
>>>classFieldTypes(Enum):...name=0...value=1...size=2...>>>FieldTypes.value.size<FieldTypes.size: 2>>>>FieldTypes.size.value2
Changed in version 3.5.
The__members__ attribute is only available on the class.
If you give yourEnum subclass extra methods, like thePlanetclass above, those methods will show up in adir() of the member,but not of the class:
>>>dir(Planet)['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']>>>dir(Planet.EARTH)['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']
The__new__() method will only be used for the creation of theEnum members – after that it is replaced. Any custom__new__()method must create the object and set the_value_ attributeappropriately.
If you wish to change howEnum members are looked up you should eitherwrite a helper function or aclassmethod() for theEnumsubclass.
