There have been many posts here about enums in python, but none seem to be both type safe and simple. Here is my attempt at it. Please let me know if you see anything obviously wrong with it.
def typeSafeEnum(enumName, *sequential):
topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential))))
vals = map(lambda x: type(x,(topLevel,),{}), sequential)
for k, v in zip(sequential, vals):
setattr(topLevel, k, v())
return topLevel
Then to test it:
Colors = typeSafeEnum('Colors', 'RED', 'GREEN', 'BLUE')
if __name__ == '__main__':
x = Colors.RED
assert isinstance(x, Colors)
enum
module and it's available viapip install enum34
for older versions. \$\endgroup\$