Created
February 1, 2012 23:50
-
-
Save anthonywu/1720225 to your computer and use it in GitHub Desktop.
Python enum classes
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
# Author: Anthony Wu | |
# A quick way to make Python enum classes. | |
# Uses range/enumerate to quickly generate a list of enumerated values, | |
# but only safe/useful for your application logic where you don't have | |
# to persist these values to a data store. | |
# Example A: hard code enum classes | |
class Fruits(object): | |
(Apple, | |
Orange, | |
Pear, | |
Strawberry, | |
) = range(1,5) | |
print Fruits.Apple # 1 | |
print Fruits.Orange # 2 | |
print Fruits.Pear # 3 | |
print Fruits.Strawberry # 4 | |
# Example B: a helper function that returns an enum class | |
def make_enum_class(*enum_names): | |
class E(object): | |
_human = {} | |
@classmethod | |
def humanize(cls, value): | |
return cls._human.get(value, "[Undefined]") | |
for i, n in enumerate(enum_names, 1): | |
setattr(E, n, i) | |
E._human[i] = n | |
return E | |
MagicFruits = make_enum_class( | |
"Apple", | |
"Orange", | |
"Pear", | |
"Strawberry" | |
) | |
for e in (MagicFruits.Apple, MagicFruits.Orange, MagicFruits.Pear, MagicFruits.Strawberry): | |
print "%d --> %s" % (e, MagicFruits.humanize(e)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment