After this answer by Alec Thomas, I am using the following to create enumerations:
def enum(*sequential):
enums = dict(zip(sequential, range(len(sequential))))
return type('Enum', (), enums)
I would like to be able to obtain the length of one of these enums. For example, I can write
>>> Suit = enum('spades', 'hearts', 'diamonds', 'clubs')
>>> Suit.spades
0
>>> Suit.hearts
1
>>> Suit.diamonds
2
>>> Suit.clubs
3
but there’s no way to list all of the enumeration values at runtime. I’d like to be able to do something like
>>> [s for s in Suit]
[0, 1, 2, 3]
I’ve tried assigning enum['__iter__']
within the enum()
function, but I don’t know what kind of object I need to assign:
def enum(*sequential):
enums = dict(zip(sequential, range(len(sequential))))
enums['__iter__'] = iter(range(len(sequential)))
return type('Enum', (), enums)
gives
>>> [s for s in Suit]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not iterable
How can I give an enum
the ability to list its members? (Even just the ability for the enum to report its length would suffice, since then the members are simply the elements of range(len(Suit))
.)