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.
1 2 3 4 | def enum(names):
"Create a simple enumeration having similarities to C."
return type('enum', (), dict(map(reversed, enumerate(
names.replace(',', ' ').split())), __slots__=()))()
|
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.
See recipe 577024
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.@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__
.