Using Enums in Python
Jump to navigation
Jump to search
Examples
See - http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
Here are a few of these...
One
class Animal:
DOG=1
CAT=2
x = Animal.DOG
Two
def enum(**enums):
return type('Enum', (), enums)
Used like so:
>>> Numbers = enum(ONE=1, TWO=2, THREE='three') >>> Numbers.ONE 1 >>> Numbers.TWO 2 >>> Numbers.THREE 'three'
Three
Provide automatic enumeration with something like this:
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
Used like so:
>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
0
>>> Numbers.ONE
1
Four
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
...
Animals = Enum(["DOG", "CAT", "Horse"])
print Animals.DOG
This can be further improved by overriding __setattr__(self, name, value) and maybe __delattr__(self, name) so that if you accidentally write Animals.DOG = CAT, it won't silently succeed.
Five
dog, cat, rabbit = range(3)
Five
class Animal:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return "<Animal: %s>" % self
Animal.DOG = Animal("dog")
Animal.CAT = Animal("cat")
>>> x = Animal.DOG
>>> x
<Animal: dog>
>>> x == 1
False