Created
December 10, 2013 08:54
-
-
Save jmorenoamor/7887594 to your computer and use it in GitHub Desktop.
Enumerations in Python
This file contains hidden or 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
################################################################################ | |
# Enumerations in Python | |
################################################################################ | |
def enum(*sequential, **named): | |
enums = dict(zip(sequential, range(len(sequential))), **named) | |
reverse = dict((value, key) for key, value in enums.iteritems()) | |
enums['reverse_mapping'] = reverse | |
return type('Enum', (), enums) | |
Numbers = enum(ONE=1, TWO=2, THREE='three') | |
Numbers.ONE | |
Numbers.TWO | |
Numbers.THREE | |
# Automatic enumeration with something like this: | |
Numbers = enum('ZERO', 'ONE', 'TWO') | |
Numbers.ZERO | |
Numbers.ONE | |
# Converting the values back to names can be added this way: | |
Numbers.reverse_mapping['three'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment