Skip to content

Instantly share code, notes, and snippets.

@zenubis
Created April 8, 2014 03:09
Show Gist options
  • Save zenubis/10086329 to your computer and use it in GitHub Desktop.
Save zenubis/10086329 to your computer and use it in GitHub Desktop.
python enum
#taken from http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
def enum(**enums):
return type('Enum', (), enums)
# which is used like so:
#
#>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
#>>> Numbers.ONE
#1
#>>> Numbers.TWO
#2
#>>> Numbers.THREE
#'three'
#You can also easily support automatic enumeration with something like this:
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
#and used like so:
#
#>>> Numbers = enum('ZERO', 'ONE', 'TWO')
#>>> Numbers.ZERO
#0
#>>> Numbers.ONE
#1
#Support for converting the values back to names can be added this way:
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)
#This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw KeyError if the reverse mapping doesn't exist. With the first example:
#
#>>> Numbers.reverse_mapping['three']
#'THREE'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment