I started with this code snippet, which, by my understanding, is essentially a class-factory of sorts to emulate an "enum" type from other languages:
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
(which I took from here: How can I represent an 'Enum' in Python? )
I get how it works, and it does, but I would like to make my dynamically generated classes, which are of type 'Enum', iterable so that i can do the following in order to do a sanity check:
MyEnum = enum('FOO', 'BAR', 'JIMMY')
def func(my_enum_value): # expects one of the MyEnum values
if not my_enum_value in MyEnum:
raise SomeSortOfException
However, in order to make that sanity check work, I need to make MyEnum iterable. I read here: http://pydanny.blogspot.com/2007/10/required-methods-to-make-class-iterable.html that I needed to add iter len contains and getitem methods to something in order to make it iterable. I started down this road (rewriting the enum code) but got stuck:
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
enums['_enums'] = enums.copy() # (so I'd have them in the Class in order to use for the methods I'll be implementing to make it iterable)
Enum = type('Enum', (), enums)
Enum.__iter__ = #Er, how do I do this? Guess I'll ask SO
Enum.__len__ = # etc.
# . . .
return Enum
SO, how do I make my generated Enum classes iterable so I can use the 'in' word with them? This isn't life or death for me, but I'm learning a ton of Python by doing this.