Another, very simple, implementation of an enum in Python, using namedtuple
:
from collections import namedtuple
def enum(*keys):
return namedtuple('Enum', keys)(*keys)
MyEnum = enum('FOO', 'BAR', 'BAZ')
or, alternatively,
# With sequential number values
def enum(*keys):
return namedtuple('Enum', keys)(*range(len(keys)))
# From a dict / keyword args
def enum(**kwargs):
return namedtuple('Enum', kwargs.keys())(*kwargs.values())
# Example for dictionary param:
values = {"Salad": 20, "Carrot": 99, "Tomato": "No i'm not"}
Vegetables= enum(**values)
# >>> print(Vegetables.Tomato) 'No i'm not'
# Example for keyworded params:
Fruits = enum(Apple="Steve Jobs", Peach=1, Banana=2)
# >>> print(Fruits.Apple) 'Steve Jobs'
Like the method above that subclasses set
, this allows:
'FOO' in MyEnum
other = MyEnum.FOO
assert other == MyEnum.FOO
But has more flexibility as it can have different keys and values. This allows
MyEnum.FOO < MyEnum.BAR
to act as is expected if you use the version that fills in sequential number values.