Enums in Python

written on Friday, May 10, 2013 by

Until now, if you wanted to use enumeration types in Python you had to fall back to a class-attribute approach:

>>> class Color(object):
...    RED = 1
...    GREEN = 2
...    BLUE = 3
>>> print(Color.RED)

This has different downsides, for example with representation (Color.RED is represented as an integer, not as a color type) and comparability (Color.RED will be equal to HttpResponses.INTERNAL_SERVER_ERROR if both have the value 1).

Enter PEP 435, which was accepted by Guido today. It specifies a new base class which can be subclassed to create a custom enumeration.



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


>>> print(
>>> print(repr(
< 1>


>>> for color in Color:
...   print(color)

Programmatic access:

>>> Color(1)
>>> Color['blue']

There's even more awesome stuff you can do with those enums. For more information, refer to the proposal.

Can I already use this?

Yes and no. The PEP will be included in Python 3.4. But if you want to start using it right now, you can use the flufl.enum library which is the base implementation for PEP 435 and works for Python ≥2.7 and ≥3.2.

This entry was tagged python