Tag Archives: Python3

Python 3: An Intro to Enumerations

Python added the enum module to the standard library in version 3.4. The Python documentation describes an enum like this:

An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.

Let’s look at how you might create an Enum object:

>>> from enum import Enum
>>> class AnimalEnum(Enum):
        HORSE = 1
        COW = 2
        CHICKEN = 3
        DOG = 4
>>> print(AnimalEnum.CHICKEN)
>>> print(repr(AnimalEnum.CHICKEN))
<animalenum .CHICKEN: 3>

Here we create an Enumeration class called AnimalEnum. Inside the class, we create class attributes called enumeration members, which are constants. When you try to print out an enum member, you will just get back the same string. But if you print out the repr of the enum member, you will get the enum member and its value.

If you try to modify an enum member, Python will raise an AttributeError:

>>> AnimalEnum.CHICKEN = 5
Traceback (most recent call last):
  Python Shell, prompt 5, line 1
  File "C:\Users\mike\AppData\Local\Programs\PYTHON\PYTHON36-32\Lib\enum.py", line 361, in __setattr__
    raise AttributeError('Cannot reassign members.')
builtins.AttributeError: Cannot reassign members.

Continue reading Python 3: An Intro to Enumerations