Enums

This notebook is an introduction to Python Enums as introduced in Python 3.4 and subsequently backported to other version of Python. More details can be found in the library documentation: https://docs.python.org/3.4/library/enum.html

Enumerations are sets of symbolic names bound to unique, constant values.

Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.

A simple example is:

from enum import Enum
class Color(Enum):
    red = 1
    green = 2
    blue = 3

Let's walk through the example above. First you import the Enum library with the line:

from enum import Enum

Then you subclass Enum to create your own enumerated class with the values listed within the class:

class Color(Enum):
    red = 1
    green = 2
    blue = 3

Try it below, create your own Enum.


In [ ]:
from enum import Enum

In [ ]:
class MyEnum(Enum):
    first = 1
    second = 2
    third = 3

Nomenclature

Python has a specific nomenclature for enums.

The class Color is an enumeration (or enum)

The attributes Color.red, Color.green, etc., are enumeration members (or enum members).

The enum members have names and values (the name of Color.red is red, the value of Color.blue is 3, etc.)

Printing and Representing Enums

Enum types have human readable string representations for print and repr:


In [ ]:
print(MyEnum.first)

In [ ]:
print(repr(MyEnum.first))

The type of an enumeration member is the enumeration it belongs to:


In [ ]:
type(MyEnum.first)

In [ ]:


In [ ]:

Alternative way to create an Enum

There is an alternative way to create and Enum, that matches Python's NamedTuple:

Colour = Enum('Colour', 'red, green')

Try it below:


In [ ]:
SecondEnum = Enum('SecondEnum', 'first, second, third')
print(SecondEnum.first)

In [ ]:

Autonumbered Enums

If you come from a background in another programming language you might expect enums to autonumber. They don't by default, but you can easily create your own that does:

class AutoNumber(Enum):
    def __new__(cls):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value = value
        return obj
    def __int__(self):
        return self._value

class Color(AutoNumber):
    red = ()
    green = ()
    blue = ()

In [ ]:


In [ ]:


In [ ]: