Created
July 28, 2011 17:44
-
-
Save teh/1112080 to your computer and use it in GitHub Desktop.
Another enum hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# inspired by https://bitbucket.org/tebeka/pythonwise/src/c68764fa3a8b/enum.py | |
def enum(name, members, bitmask=False): | |
''' | |
>>> Hi = enum('Hi', 'a b c') | |
>>> print Hi.a | |
1 | |
>>> print Hi.c | |
3 | |
>>> Hi2 = enum('Hi2', 'a b c', bitmask=True) | |
>>> print Hi2.a | |
1 | |
>>> print Hi2.c | |
4 | |
''' | |
value = (lambda i: 1 << i) if bitmask else (lambda i: i + 1) | |
enum = type( | |
name, | |
(object,), | |
dict((member, value(i)) for i, member in enumerate(members.split())) | |
) | |
return enum | |
if __name__ == "__main__": | |
from doctest import testmod | |
testmod(verbose=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment