Welcome, guest | Sign In | My Account | Store | Cart

If you want a small code snippet for enumerations in Python and the following code is sufficient for your needs, please go ahead and use it! Running the code is as simple as this: STATE = enum('GET_QUIZ, GET_VERSE, TEACH')

This recipe was edited and adapted after the author was inspired by seeing other, better enum recipes lying around.

Python, 4 lines
def enum(names):
    "Create a simple enumeration having similarities to C."
    return type('enum', (), dict(map(reversed, enumerate(
        names.replace(',', ' ').split())), __slots__=()))()


Eric-Olivier LE BIGOT 12 years, 10 months ago  # | flag

This might work for know, but this is a coincidence: the official documentation reads, about locals():

"Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter."

Instead of modifying locals(), you could define a constructor that performs a setattr(self, name, enum_value) for each name.

Gabriel Genellina 12 years, 10 months ago  # | flag
Stephen Chappell (author) 12 years, 10 months ago  # | flag

Thank you! Your recipe is perfect. I was wondering, though: there is __slots__ = (), and the documentation does not appear to have anything that states what this means. Do you have a link to the Python docs that tells was assigning an empty tuple to __slots__ is supposed to do? I think I understand what is happening but would like confirmation from the documentation itself.

Martin Miller 11 years, 11 months ago  # | flag

@Stephen Chappell: By default, instances of both old and new-style classes have a dictionary called __dict__ for attribute storage. In new-style classes assigning a sequence to the __slots__ class variable saves space because it prevents the automatic creation of this dictionary for each instance of the class. Instances also cannot be assigned new variables (instance attributes) not listed in the __slots__ definition. Assigning __slots__ an empty tuple means the class has no additional attributes while saving the maximum amount of space.

Paraphrased from the online documentation for __slots__.

Created by Stephen Chappell on Mon, 25 Jan 2010 (MIT)
Python recipes (4591)
Stephen Chappell's recipes (233)

Required Modules

  • (none specified)

Other Information and Tasks