How to create an enum in Python?

Python does not have any syntax for creating enums (it’s proposal was rejected), but there are some alternatives.

1. Using a class

class Numbers(object):
    ONE = 1
    TWO = 2
    THREE = 3
 
assert Numbers.ONE == 1
assert Numbers.TWO == 2
assert Numbers.THREE == 3

2. Use a function that dynamically creates a new class

def enum(**enums):
    return type('Enum', (object,), enums)
 
Numbers = enum(ONE=1, TWO=2, THREE=3)
 
assert Numbers.ONE == 1
assert Numbers.TWO == 2
assert Numbers.THREE == 3

3. Create a new object that extends Python’s set

class Enum(set):
    def __getattr__(self, name):
        if name in self:
            return name
        raise AttributeError
 
Numbers = Enum( "ONE TWO THREE".split() )
 
error = False
try:
    print Numbers.ONE
    print Numbers.TWO
    print Numbers.THREE
except:
    error = True
assert error == False
 
try:
    print Numbers.FOUR
except:
    error = True
assert error == True
Both comments and pings are currently closed.

6 Responses to “How to create an enum in Python?”

  1. Cameron Hayne says:

    I used method #2 (a function that dynamically creates a new class) but in a more elaborate way that satisfies the several requirements I had for enums that were to be part of an API.
    See my blog post: http://franktheblue.blogspot.com/2011/05/enums-in-python-more-flexible-and.html

  2. admin says:

    Thanks Cameron. Nice post!

  3. Carlo Pires says:

    As of python 2.6 enums can be created using namedtuples. See http://bit.ly/qBJTpq

  4. admin says:

    Thanks Carlo

  5. Genffe says:

    thanks for your source code.