<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p>

<p>How can I represent the equivalent of an Enum in Python?  </p>

[{'answer_id': 36937, 'author': 'Alexandru Nedelcu', 'author_id': 3280, 'author_profile': 'https://Stackoverflow.com/users/3280', 'pm_score': 10, 'selected': False, 'text': '<p>Before PEP 435, Python didn\'t have an equivalent but you could implement your own.</p>\n<p>Myself, I like keeping it simple (I\'ve seen some horribly complex examples on the net), something like this ...</p>\n<pre><code>class Animal:\n    DOG = 1\n    CAT = 2\n\nx = Animal.DOG\n</code></pre>\n<hr />\n<p>In Python 3.4 (<a href="http://www.python.org/dev/peps/pep-0435/" rel="noreferrer">PEP 435</a>), you can make <a href="https://docs.python.org/3/library/enum.html" rel="noreferrer">Enum</a> the base class.  This gets you a little bit of extra functionality, described in the PEP.  For example, enum members are distinct from integers, and they are composed of a <code>name</code> and a <code>value</code>.</p>\n<pre><code>from enum import Enum\n\nclass Animal(Enum):\n    DOG = 1\n    CAT = 2\n\nprint(Animal.DOG)\n# &lt;Animal.DOG: 1&gt;\n\nprint(Animal.DOG.value)\n# 1\n\nprint(Animal.DOG.name)\n# &quot;DOG&quot;\n</code></pre>\n<hr />\n<p>If you don\'t want to type the values, use the following shortcut:</p>\n<pre><code>class Animal(Enum):\n    DOG, CAT = range(2)\n</code></pre>\n<hr />\n<p><code>Enum</code> implementations <a href="https://docs.python.org/3/library/enum.html#how-are-enums-different" rel="noreferrer">can be converted to lists and are iterable</a>. The order of its members is the declaration order and has nothing to do with their values. For example:</p>\n<pre><code>class Animal(Enum):\n    DOG = 1\n    CAT = 2\n    COW = 0\n\nlist(Animal)\n# [&lt;Animal.DOG: 1&gt;, &lt;Animal.CAT: 2&gt;, &lt;Animal.COW: 0&gt;]\n\n[animal.value for animal in Animal]\n# [1, 2, 0]\n\nAnimal.CAT in Animal\n# True\n</code></pre>\n'}, {'answer_id': 36940, 'author': 'dguaraglia', 'author_id': 2384, 'author_profile': 'https://Stackoverflow.com/users/2384', 'pm_score': 5, 'selected': False, 'text': '<p>Hmmm... I suppose the closest thing to an enum would be a dictionary, defined either like this:</p>\n\n<pre><code>months = {\n    \'January\': 1,\n    \'February\': 2,\n    ...\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>months = dict(\n    January=1,\n    February=2,\n    ...\n)\n</code></pre>\n\n<p>Then, you can use the symbolic name for the constants like this:</p>\n\n<pre><code>mymonth = months[\'January\']\n</code></pre>\n\n<p>There are other options, like a list of tuples, or a tuple of tuples, but the dictionary is the only one that provides you with a "symbolic" (constant string) way to access the \nvalue.</p>\n\n<p>Edit: I like Alexandru\'s answer too!</p>\n'}, {'answer_id': 37000, 'author': 'dF.', 'author_id': 3002, 'author_profile': 'https://Stackoverflow.com/users/3002', 'pm_score': 6, 'selected': False, 'text': '<p>Python doesn\'t have a built-in equivalent to <code>enum</code>, and other answers have ideas for implementing your own (you may also be interested in the <a href="http://code.activestate.com/recipes/67107/" rel="noreferrer">over the top version</a> in the Python cookbook).</p>\n\n<p>However, in situations where an <code>enum</code> would be called for in C, I usually end up <strong><em>just using simple strings</em></strong>: because of the way objects/attributes are implemented, (C)Python is optimized to work very fast with short strings anyway, so there wouldn\'t really be any performance benefit to using integers. To guard against typos / invalid values you can insert checks in selected places.</p>\n\n<pre><code>ANIMALS = [\'cat\', \'dog\', \'python\']\n\ndef take_for_a_walk(animal):\n    assert animal in ANIMALS\n    ...\n</code></pre>\n\n<p>(One disadvantage compared to using a class is that you lose the benefit of autocomplete)</p>\n'}, {'answer_id': 37081, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 8, 'selected': False, 'text': "<p>If you need the numeric values, here's the quickest way:</p>\n\n<pre><code>dog, cat, rabbit = range(3)\n</code></pre>\n\n<p>In Python 3.x you can also add a starred placeholder at the end, which will soak up all the remaining values of the range in case you don't mind wasting memory and cannot count:</p>\n\n<pre><code>dog, cat, rabbit, horse, *_ = range(100)\n</code></pre>\n"}, {'answer_id': 38092, 'author': 'Aaron Maenpaa', 'author_id': 2603, 'author_profile': 'https://Stackoverflow.com/users/2603', 'pm_score': 6, 'selected': False, 'text': '<p>The typesafe enum pattern which was used in Java pre-JDK 5 has a\nnumber of advantages. Much like in Alexandru\'s answer, you create a\nclass and class level fields are the enum values; however, the enum\nvalues are instances of the class rather than small integers. This has\nthe advantage that your enum values don\'t inadvertently compare equal\nto small integers, you can control how they\'re printed, add arbitrary\nmethods if that\'s useful and make assertions using isinstance:</p>\n\n<pre><code>class Animal:\n   def __init__(self, name):\n       self.name = name\n\n   def __str__(self):\n       return self.name\n\n   def __repr__(self):\n       return "&lt;Animal: %s&gt;" % self\n\nAnimal.DOG = Animal("dog")\nAnimal.CAT = Animal("cat")\n\n&gt;&gt;&gt; x = Animal.DOG\n&gt;&gt;&gt; x\n&lt;Animal: dog&gt;\n&gt;&gt;&gt; x == 1\nFalse\n</code></pre>\n\n<hr>\n\n<p>A recent <a href="http://mail.python.org/pipermail/python-dev/2010-November/105873.html" rel="noreferrer">thread on python-dev</a> pointed out there are a couple of enum libraries in the wild, including:</p>\n\n<ul>\n<li><a href="http://packages.python.org/flufl.enum/docs/using.html" rel="noreferrer">flufl.enum</a></li>\n<li><a href="http://pypi.python.org/pypi/lazr.enum" rel="noreferrer">lazr.enum</a></li>\n<li>... and the imaginatively named <a href="http://pypi.python.org/pypi/enum/" rel="noreferrer">enum</a></li>\n</ul>\n'}, {'answer_id': 38762, 'author': 'tuxedo', 'author_id': 3286, 'author_profile': 'https://Stackoverflow.com/users/3286', 'pm_score': 4, 'selected': False, 'text': "<p>davidg recommends using dicts.  I'd go one step further and use sets:</p>\n\n<pre><code>months = set('January', 'February', ..., 'December')\n</code></pre>\n\n<p>Now you can test whether a value matches one of the values in the set like this:</p>\n\n<pre><code>if m in months:\n</code></pre>\n\n<p>like dF, though, I usually just use string constants in place of enums.</p>\n"}, {'answer_id': 99347, 'author': 'Rick Harris', 'author_id': 18460, 'author_profile': 'https://Stackoverflow.com/users/18460', 'pm_score': 3, 'selected': False, 'text': '<p>Alexandru\'s suggestion of using class constants for enums works quite well. </p>\n\n<p>I also like to add a dictionary for each set of constants to lookup a human-readable string representation. </p>\n\n<p>This serves two purposes: a) it provides a simple way to pretty-print your enum and b) the dictionary logically groups the constants so that you can test for membership.</p>\n\n<pre><code>class Animal:    \n  TYPE_DOG = 1\n  TYPE_CAT = 2\n\n  type2str = {\n    TYPE_DOG: "dog",\n    TYPE_CAT: "cat"\n  }\n\n  def __init__(self, type_):\n    assert type_ in self.type2str.keys()\n    self._type = type_\n\n  def __repr__(self):\n    return "&lt;%s type=%s&gt;" % (\n        self.__class__.__name__, self.type2str[self._type].upper())\n</code></pre>\n'}, {'answer_id': 107973, 'author': 'user18695', 'author_id': 18695, 'author_profile': 'https://Stackoverflow.com/users/18695', 'pm_score': 5, 'selected': False, 'text': "<pre><code>def M_add_class_attribs(attribs):\n    def foo(name, bases, dict_):\n        for v, k in attribs:\n            dict_[k] = v\n        return type(name, bases, dict_)\n    return foo\n\ndef enum(*names):\n    class Foo(object):\n        __metaclass__ = M_add_class_attribs(enumerate(names))\n        def __setattr__(self, name, value):  # this makes it read-only\n            raise NotImplementedError\n    return Foo()\n</code></pre>\n\n<p>Use it like this:  </p>\n\n<pre><code>Animal = enum('DOG', 'CAT')\nAnimal.DOG # returns 0\nAnimal.CAT # returns 1\nAnimal.DOG = 2 # raises NotImplementedError\n</code></pre>\n\n<p>if you just want unique symbols and don't care about the values, replace this line:  </p>\n\n<pre><code>__metaclass__ = M_add_class_attribs(enumerate(names))\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>__metaclass__ = M_add_class_attribs((object(), name) for name in names)\n</code></pre>\n"}, {'answer_id': 220537, 'author': 'Jake', 'author_id': 24730, 'author_profile': 'https://Stackoverflow.com/users/24730', 'pm_score': 2, 'selected': False, 'text': "<p>It's funny, I just had a need for this the other day and I couldnt find an implementation worth using... so I wrote my own:</p>\n\n<pre><code>import functools\n\nclass EnumValue(object):\n    def __init__(self,name,value,type):\n        self.__value=value\n        self.__name=name\n        self.Type=type\n    def __str__(self):\n        return self.__name\n    def __repr__(self):#2.6 only... so change to what ever you need...\n        return '{cls}({0!r},{1!r},{2})'.format(self.__name,self.__value,self.Type.__name__,cls=type(self).__name__)\n\n    def __hash__(self):\n        return hash(self.__value)\n    def __nonzero__(self):\n        return bool(self.__value)\n    def __cmp__(self,other):\n        if isinstance(other,EnumValue):\n            return cmp(self.__value,other.__value)\n        else:\n            return cmp(self.__value,other)#hopefully their the same type... but who cares?\n    def __or__(self,other):\n        if other is None:\n            return self\n        elif type(self) is not type(other):\n            raise TypeError()\n        return EnumValue('{0.Name} | {1.Name}'.format(self,other),self.Value|other.Value,self.Type)\n    def __and__(self,other):\n        if other is None:\n            return self\n        elif type(self) is not type(other):\n            raise TypeError()\n        return EnumValue('{0.Name} &amp; {1.Name}'.format(self,other),self.Value&amp;other.Value,self.Type)\n    def __contains__(self,other):\n        if self.Value==other.Value:\n            return True\n        return bool(self&amp;other)\n    def __invert__(self):\n        enumerables=self.Type.__enumerables__\n        return functools.reduce(EnumValue.__or__,(enum for enum in enumerables.itervalues() if enum not in self))\n\n    @property\n    def Name(self):\n        return self.__name\n\n    @property\n    def Value(self):\n        return self.__value\n\nclass EnumMeta(type):\n    @staticmethod\n    def __addToReverseLookup(rev,value,newKeys,nextIter,force=True):\n        if value in rev:\n            forced,items=rev.get(value,(force,()) )\n            if forced and force: #value was forced, so just append\n                rev[value]=(True,items+newKeys)\n            elif not forced:#move it to a new spot\n                next=nextIter.next()\n                EnumMeta.__addToReverseLookup(rev,next,items,nextIter,False)\n                rev[value]=(force,newKeys)\n            else: #not forcing this value\n                next = nextIter.next()\n                EnumMeta.__addToReverseLookup(rev,next,newKeys,nextIter,False)\n                rev[value]=(force,newKeys)\n        else:#set it and forget it\n            rev[value]=(force,newKeys)\n        return value\n\n    def __init__(cls,name,bases,atts):\n        classVars=vars(cls)\n        enums = classVars.get('__enumerables__',None)\n        nextIter = getattr(cls,'__nextitr__',itertools.count)()\n        reverseLookup={}\n        values={}\n\n        if enums is not None:\n            #build reverse lookup\n            for item in enums:\n                if isinstance(item,(tuple,list)):\n                    items=list(item)\n                    value=items.pop()\n                    EnumMeta.__addToReverseLookup(reverseLookup,value,tuple(map(str,items)),nextIter)\n                else:\n                    value=nextIter.next()\n                    value=EnumMeta.__addToReverseLookup(reverseLookup,value,(str(item),),nextIter,False)#add it to the reverse lookup, but don't force it to that value\n\n            #build values and clean up reverse lookup\n            for value,fkeys in reverseLookup.iteritems():\n                f,keys=fkeys\n                for key in keys:\n                    enum=EnumValue(key,value,cls)\n                    setattr(cls,key,enum)\n                    values[key]=enum\n                reverseLookup[value]=tuple(val for val in values.itervalues() if val.Value == value)\n        setattr(cls,'__reverseLookup__',reverseLookup)\n        setattr(cls,'__enumerables__',values)\n        setattr(cls,'_Max',max([key for key in reverseLookup] or [0]))\n        return super(EnumMeta,cls).__init__(name,bases,atts)\n\n    def __iter__(cls):\n        for enum in cls.__enumerables__.itervalues():\n            yield enum\n    def GetEnumByName(cls,name):\n        return cls.__enumerables__.get(name,None)\n    def GetEnumByValue(cls,value):\n        return cls.__reverseLookup__.get(value,(None,))[0]\n\nclass Enum(object):\n    __metaclass__=EnumMeta\n    __enumerables__=None\n\nclass FlagEnum(Enum):\n    @staticmethod\n    def __nextitr__():\n        yield 0\n        for val in itertools.count():\n            yield 2**val\n\ndef enum(name,*args):\n    return EnumMeta(name,(Enum,),dict(__enumerables__=args))\n</code></pre>\n\n<p>Take it or leave it, it did what I needed it to do :)</p>\n\n<p>Use it like:</p>\n\n<pre><code>class Air(FlagEnum):\n    __enumerables__=('None','Oxygen','Nitrogen','Hydrogen')\n\nclass Mammals(Enum):\n    __enumerables__=('Bat','Whale',('Dog','Puppy',1),'Cat')\nBool = enum('Bool','Yes',('No',0))\n</code></pre>\n"}, {'answer_id': 505457, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>What I use:</p>\n\n<pre><code>class Enum(object):\n    def __init__(self, names, separator=None):\n        self.names = names.split(separator)\n        for value, name in enumerate(self.names):\n            setattr(self, name.upper(), value)\n    def tuples(self):\n        return tuple(enumerate(self.names))\n</code></pre>\n\n<p>How to use:</p>\n\n<pre><code>&gt;&gt;&gt; state = Enum(\'draft published retracted\')\n&gt;&gt;&gt; state.DRAFT\n0\n&gt;&gt;&gt; state.RETRACTED\n2\n&gt;&gt;&gt; state.FOO\nTraceback (most recent call last):\n   File "&lt;stdin&gt;", line 1, in &lt;module&gt;\nAttributeError: \'Enum\' object has no attribute \'FOO\'\n&gt;&gt;&gt; state.tuples()\n((0, \'draft\'), (1, \'published\'), (2, \'retracted\'))\n</code></pre>\n\n<p>So this gives you integer constants like state.PUBLISHED and the two-tuples to use as choices in Django models.</p>\n'}, {'answer_id': 1529241, 'author': 'Ashwin Nanjappa', 'author_id': 1630, 'author_profile': 'https://Stackoverflow.com/users/1630', 'pm_score': 7, 'selected': False, 'text': '<p>The best solution for you would depend on what you require from your <em>fake</em> <strong><code>enum</code></strong>.</p>\n\n<p><strong>Simple enum:</strong></p>\n\n<p>If you need the <strong><code>enum</code></strong> as only a list of <em>names</em> identifying different <em>items</em>, the solution by <strong>Mark Harrison</strong> (above) is great:</p>\n\n<pre><code>Pen, Pencil, Eraser = range(0, 3)\n</code></pre>\n\n<p>Using a <strong><code>range</code></strong> also allows you to set any <em>starting value</em>:</p>\n\n<pre><code>Pen, Pencil, Eraser = range(9, 12)\n</code></pre>\n\n<p>In addition to the above, if you also require that the items belong to a <em>container</em> of some sort, then embed them in a class:</p>\n\n<pre><code>class Stationery:\n    Pen, Pencil, Eraser = range(0, 3)\n</code></pre>\n\n<p>To use the enum item, you would now need to use the container name and the item name:</p>\n\n<pre><code>stype = Stationery.Pen\n</code></pre>\n\n<p><strong>Complex enum:</strong></p>\n\n<p>For long lists of enum or more complicated uses of enum, these solutions will not suffice. You could look to the recipe by Will Ware for <em>Simulating Enumerations in Python</em> published in the <em>Python Cookbook</em>. An online version of that is available <a href="http://code.activestate.com/recipes/67107/" rel="noreferrer">here</a>.</p>\n\n<p><strong>More info:</strong></p>\n\n<p><a href="http://www.python.org/dev/peps/pep-0354/" rel="noreferrer"><em>PEP 354: Enumerations in Python</em></a> has the interesting details of a proposal for enum in Python and why it was rejected.</p>\n'}, {'answer_id': 1587932, 'author': 'Natim', 'author_id': 186202, 'author_profile': 'https://Stackoverflow.com/users/186202', 'pm_score': 2, 'selected': False, 'text': '<p>Use the following.</p>\n\n<pre><code>TYPE = {\'EAN13\':   u\'EAN-13\',\n        \'CODE39\':  u\'Code 39\',\n        \'CODE128\': u\'Code 128\',\n        \'i25\':     u\'Interleaved 2 of 5\',}\n\n&gt;&gt;&gt; TYPE.items()\n[(\'EAN13\', u\'EAN-13\'), (\'i25\', u\'Interleaved 2 of 5\'), (\'CODE39\', u\'Code 39\'), (\'CODE128\', u\'Code 128\')]\n&gt;&gt;&gt; TYPE.keys()\n[\'EAN13\', \'i25\', \'CODE39\', \'CODE128\']\n&gt;&gt;&gt; TYPE.values()\n[u\'EAN-13\', u\'Interleaved 2 of 5\', u\'Code 39\', u\'Code 128\']\n</code></pre>\n\n<p>I used that for <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow noreferrer">Django</a> model choices, and it looks very pythonic. It is not really an Enum, but it does the job.</p>\n'}, {'answer_id': 1695250, 'author': 'Alec Thomas', 'author_id': 7980, 'author_profile': 'https://Stackoverflow.com/users/7980', 'pm_score': 13, 'selected': True, 'text': '<p><a href="https://docs.python.org/3/library/enum.html" rel="noreferrer">Enums</a> have been added to Python 3.4 as described in <a href="http://www.python.org/dev/peps/pep-0435/" rel="noreferrer">PEP 435</a>.  It has also been <a href="https://pypi.python.org/pypi/enum34" rel="noreferrer">backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4</a> on pypi.</p>\n<p>For more advanced Enum techniques try the <a href="https://pypi.python.org/pypi/aenum" rel="noreferrer">aenum library</a> (2.7, 3.3+, same author as <code>enum34</code>. Code is not perfectly compatible between py2 and py3, e.g. you\'ll need <a href="https://stackoverflow.com/a/25982264/57461"><code>__order__</code> in python 2</a>).</p>\n<ul>\n<li>To use <code>enum34</code>, do <code>$ pip install enum34</code></li>\n<li>To use <code>aenum</code>, do <code>$ pip install aenum</code></li>\n</ul>\n<p>Installing <code>enum</code> (no numbers) will install a completely different and incompatible version.</p>\n<hr />\n<pre><code>from enum import Enum     # for enum34, or the stdlib version\n# from aenum import Enum  # for the aenum version\nAnimal = Enum(\'Animal\', \'ant bee cat dog\')\n\nAnimal.ant  # returns &lt;Animal.ant: 1&gt;\nAnimal[\'ant\']  # returns &lt;Animal.ant: 1&gt; (string lookup)\nAnimal.ant.name  # returns \'ant\' (inverse lookup)\n</code></pre>\n<p>or equivalently:</p>\n<pre><code>class Animal(Enum):\n    ant = 1\n    bee = 2\n    cat = 3\n    dog = 4\n</code></pre>\n<hr />\n<p>In earlier versions, one way of accomplishing enums is:</p>\n<pre><code>def enum(**enums):\n    return type(\'Enum\', (), enums)\n</code></pre>\n<p>which is used like so:</p>\n<pre><code>&gt;&gt;&gt; Numbers = enum(ONE=1, TWO=2, THREE=\'three\')\n&gt;&gt;&gt; Numbers.ONE\n1\n&gt;&gt;&gt; Numbers.TWO\n2\n&gt;&gt;&gt; Numbers.THREE\n\'three\'\n</code></pre>\n<p>You can also easily support automatic enumeration with something like this:</p>\n<pre><code>def enum(*sequential, **named):\n    enums = dict(zip(sequential, range(len(sequential))), **named)\n    return type(\'Enum\', (), enums)\n</code></pre>\n<p>and used like so:</p>\n<pre><code>&gt;&gt;&gt; Numbers = enum(\'ZERO\', \'ONE\', \'TWO\')\n&gt;&gt;&gt; Numbers.ZERO\n0\n&gt;&gt;&gt; Numbers.ONE\n1\n</code></pre>\n<p>Support for converting the values back to names can be added this way:</p>\n<pre><code>def enum(*sequential, **named):\n    enums = dict(zip(sequential, range(len(sequential))), **named)\n    reverse = dict((value, key) for key, value in enums.iteritems())\n    enums[\'reverse_mapping\'] = reverse\n    return type(\'Enum\', (), enums)\n</code></pre>\n<p>This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a <code>KeyError</code> if the reverse mapping doesn\'t exist. With the first example:</p>\n<pre><code>&gt;&gt;&gt; Numbers.reverse_mapping[\'three\']\n\'THREE\'\n</code></pre>\n<hr />\n<p>If you are using MyPy another way to express &quot;enums&quot; is with <a href="https://mypy.readthedocs.io/en/stable/literal_types.html#parameterizing-literals" rel="noreferrer"><code>typing.Literal</code></a>.</p>\n<p>For example:</p>\n<pre class="lang-py prettyprint-override"><code>from typing import Literal #python &gt;=3.8\nfrom typing_extensions import Literal #python 2.7, 3.4-3.7\n\n\nAnimal = Literal[\'ant\', \'bee\', \'cat\', \'dog\']\n\ndef hello_animal(animal: Animal):\n    print(f&quot;hello {animal}&quot;)\n\nhello_animal(\'rock\') # error\nhello_animal(\'bee\') # passes\n\n</code></pre>\n'}, {'answer_id': 1751697, 'author': 'PaulMcG', 'author_id': 165216, 'author_profile': 'https://Stackoverflow.com/users/165216', 'pm_score': 2, 'selected': False, 'text': '<p>I had need of some symbolic constants in pyparsing to represent left and right associativity of binary operators.  I used class constants like this:</p>\n\n<pre><code># an internal class, not intended to be seen by client code\nclass _Constants(object):\n    pass\n\n\n# an enumeration of constants for operator associativity\nopAssoc = _Constants()\nopAssoc.LEFT = object()\nopAssoc.RIGHT = object()\n</code></pre>\n\n<p>Now when client code wants to use these constants, they can import the entire enum using:</p>\n\n<pre><code>import opAssoc from pyparsing\n</code></pre>\n\n<p>The enumerations are unique, they can be tested with \'is\' instead of \'==\', they don\'t take up a big footprint in my code for a minor concept, and they are easily imported into the client code.  They don\'t support any fancy str() behavior, but so far that is in the <a href="http://c2.com/xp/YouArentGonnaNeedIt.html" rel="nofollow noreferrer">YAGNI</a> category.</p>\n'}, {'answer_id': 1753340, 'author': 'steveha', 'author_id': 166949, 'author_profile': 'https://Stackoverflow.com/users/166949', 'pm_score': 4, 'selected': False, 'text': '<p>This is the best one I have seen: "First Class Enums in Python"</p>\n\n<p><a href="http://code.activestate.com/recipes/413486/" rel="noreferrer"><a href="http://code.activestate.com/recipes/413486/" rel="noreferrer">http://code.activestate.com/recipes/413486/</a></a></p>\n\n<p>It gives you a class, and the class contains all the enums. The enums can be compared to each other, but don\'t have any particular value; you can\'t use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can\'t use it as an integer, you can\'t use it as an integer by mistake so overall I think it is a win.) Each enum is a unique value. You can print enums, you can iterate over them, you can test that an enum value is "in" the enum. It\'s pretty complete and slick.</p>\n\n<p>Edit (cfi): The above link is not Python 3 compatible. Here\'s my port of enum.py to Python 3:</p>\n\n<pre><code>def cmp(a,b):\n   if a &lt; b: return -1\n   if b &lt; a: return 1\n   return 0\n\n\ndef Enum(*names):\n   ##assert names, "Empty enums are not supported" # &lt;- Don\'t like empty enums? Uncomment!\n\n   class EnumClass(object):\n      __slots__ = names\n      def __iter__(self):        return iter(constants)\n      def __len__(self):         return len(constants)\n      def __getitem__(self, i):  return constants[i]\n      def __repr__(self):        return \'Enum\' + str(names)\n      def __str__(self):         return \'enum \' + str(constants)\n\n   class EnumValue(object):\n      __slots__ = (\'__value\')\n      def __init__(self, value): self.__value = value\n      Value = property(lambda self: self.__value)\n      EnumType = property(lambda self: EnumType)\n      def __hash__(self):        return hash(self.__value)\n      def __cmp__(self, other):\n         # C fans might want to remove the following assertion\n         # to make all enums comparable by ordinal value {;))\n         assert self.EnumType is other.EnumType, "Only values from the same enum are comparable"\n         return cmp(self.__value, other.__value)\n      def __lt__(self, other):   return self.__cmp__(other) &lt; 0\n      def __eq__(self, other):   return self.__cmp__(other) == 0\n      def __invert__(self):      return constants[maximum - self.__value]\n      def __nonzero__(self):     return bool(self.__value)\n      def __repr__(self):        return str(names[self.__value])\n\n   maximum = len(names) - 1\n   constants = [None] * len(names)\n   for i, each in enumerate(names):\n      val = EnumValue(i)\n      setattr(EnumClass, each, val)\n      constants[i] = val\n   constants = tuple(constants)\n   EnumType = EnumClass()\n   return EnumType\n\n\nif __name__ == \'__main__\':\n   print( \'\\n*** Enum Demo ***\')\n   print( \'--- Days of week ---\')\n   Days = Enum(\'Mo\', \'Tu\', \'We\', \'Th\', \'Fr\', \'Sa\', \'Su\')\n   print( Days)\n   print( Days.Mo)\n   print( Days.Fr)\n   print( Days.Mo &lt; Days.Fr)\n   print( list(Days))\n   for each in Days:\n      print( \'Day:\', each)\n   print( \'--- Yes/No ---\')\n   Confirmation = Enum(\'No\', \'Yes\')\n   answer = Confirmation.No\n   print( \'Your answer is not\', ~answer)\n</code></pre>\n'}, {'answer_id': 2182437, 'author': 'shahjapan', 'author_id': 144408, 'author_profile': 'https://Stackoverflow.com/users/144408', 'pm_score': 8, 'selected': False, 'text': '<p>Here is one implementation:</p>\n\n<pre><code>class Enum(set):\n    def __getattr__(self, name):\n        if name in self:\n            return name\n        raise AttributeError\n</code></pre>\n\n<p>Here is its usage:</p>\n\n<pre><code>Animals = Enum(["DOG", "CAT", "HORSE"])\n\nprint(Animals.DOG)\n</code></pre>\n'}, {'answer_id': 2389722, 'author': 'iobaixas', 'author_id': 287423, 'author_profile': 'https://Stackoverflow.com/users/287423', 'pm_score': 2, 'selected': False, 'text': '<p>Following the Java like enum implementation proposed by Aaron Maenpaa, I came out with the following. The idea was to make it generic and parseable.</p>\n\n<pre><code>class Enum:\n    #\'\'\'\n    #Java like implementation for enums.\n    #\n    #Usage:\n    #class Tool(Enum): name = \'Tool\'\n    #Tool.DRILL = Tool.register(\'drill\')\n    #Tool.HAMMER = Tool.register(\'hammer\')\n    #Tool.WRENCH = Tool.register(\'wrench\')\n    #\'\'\'\n\n    name = \'Enum\'    # Enum name\n    _reg = dict([])   # Enum registered values\n\n    @classmethod\n    def register(cls, value):\n        #\'\'\'\n        #Registers a new value in this enum.\n        #\n        #@param value: New enum value.\n        #\n        #@return: New value wrapper instance.\n        #\'\'\'\n        inst = cls(value)\n        cls._reg[value] = inst\n        return inst\n\n    @classmethod\n    def parse(cls, value):\n        #\'\'\'\n        #Parses a value, returning the enum instance.\n        #\n        #@param value: Enum value.\n        #\n        #@return: Value corresp instance.        \n        #\'\'\'\n        return cls._reg.get(value)    \n\n    def __init__(self, value):\n        #\'\'\'\n        #Constructor (only for internal use).\n        #\'\'\'\n        self.value = value\n\n    def __str__(self):\n        #\'\'\'\n        #str() overload.\n        #\'\'\'\n        return self.value\n\n    def __repr__(self):\n        #\'\'\'\n        #repr() overload.\n        #\'\'\'\n        return "&lt;" + self.name + ": " + self.value + "&gt;"\n</code></pre>\n'}, {'answer_id': 2458660, 'author': 'pythonic metaphor', 'author_id': 189456, 'author_profile': 'https://Stackoverflow.com/users/189456', 'pm_score': 3, 'selected': False, 'text': '<p>The enum package from <a href="http://en.wikipedia.org/wiki/Python_Package_Index" rel="noreferrer">PyPI</a> provides a robust implementation of enums. An earlier answer mentioned PEP 354; this was rejected but the proposal was implemented \n<a href="http://pypi.python.org/pypi/enum" rel="noreferrer">http://pypi.python.org/pypi/enum</a>.</p>\n\n<p>Usage is easy and elegant:</p>\n\n<pre><code>&gt;&gt;&gt; from enum import Enum\n&gt;&gt;&gt; Colors = Enum(\'red\', \'blue\', \'green\')\n&gt;&gt;&gt; shirt_color = Colors.green\n&gt;&gt;&gt; shirt_color = Colors[2]\n&gt;&gt;&gt; shirt_color &gt; Colors.red\nTrue\n&gt;&gt;&gt; shirt_color.index\n2\n&gt;&gt;&gt; str(shirt_color)\n\'green\'\n</code></pre>\n'}, {'answer_id': 2785738, 'author': 'L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳', 'author_id': 80243, 'author_profile': 'https://Stackoverflow.com/users/80243', 'pm_score': 2, 'selected': False, 'text': "<p>Why must enumerations be ints? Unfortunately, I can't think of any good looking construct to produce this without changing the Python language, so I'll use strings:</p>\n\n<pre><code>class Enumerator(object):\n    def __init__(self, name):\n        self.name = name\n\n    def __eq__(self, other):\n        if self.name == other:\n            return True\n        return self is other\n\n    def __ne__(self, other):\n        if self.name != other:\n            return False\n        return self is other\n\n    def __repr__(self):\n        return 'Enumerator({0})'.format(self.name)\n\n    def __str__(self):\n        return self.name\n\nclass Enum(object):\n    def __init__(self, *enumerators):\n        for e in enumerators:\n            setattr(self, e, Enumerator(e))\n    def __getitem__(self, key):\n        return getattr(self, key)\n</code></pre>\n\n<p>Then again maybe it's even better now that we can naturally test against strings, for the sake of configuration files or other remote input.</p>\n\n<p>Example:</p>\n\n<pre><code>class Cow(object):\n    State = Enum(\n        'standing',\n        'walking',\n        'eating',\n        'mooing',\n        'sleeping',\n        'dead',\n        'dying'\n    )\n    state = State.standing\n\nIn [1]: from enum import Enum\n\nIn [2]: c = Cow()\n\nIn [3]: c2 = Cow()\n\nIn [4]: c.state, c2.state\nOut[4]: (Enumerator(standing), Enumerator(standing))\n\nIn [5]: c.state == c2.state\nOut[5]: True\n\nIn [6]: c.State.mooing\nOut[6]: Enumerator(mooing)\n\nIn [7]: c.State['mooing']\nOut[7]: Enumerator(mooing)\n\nIn [8]: c.state = Cow.State.dead\n\nIn [9]: c.state == c2.state\nOut[9]: False\n\nIn [10]: c.state == Cow.State.dead\nOut[10]: True\n\nIn [11]: c.state == 'dead'\nOut[11]: True\n\nIn [12]: c.state == Cow.State['dead']\nOut[11]: True\n</code></pre>\n"}, {'answer_id': 2913233, 'author': 'Denis Ryzhkov', 'author_id': 350937, 'author_profile': 'https://Stackoverflow.com/users/350937', 'pm_score': 1, 'selected': False, 'text': "<pre><code>def enum( *names ):\n\n    '''\n    Makes enum.\n    Usage:\n        E = enum( 'YOUR', 'KEYS', 'HERE' )\n        print( E.HERE )\n    '''\n\n    class Enum():\n        pass\n    for index, name in enumerate( names ):\n        setattr( Enum, name, index )\n    return Enum\n</code></pre>\n"}, {'answer_id': 2976036, 'author': 'daegga', 'author_id': 358665, 'author_profile': 'https://Stackoverflow.com/users/358665', 'pm_score': 2, 'selected': False, 'text': '<p>I like the <a href="http://en.wikipedia.org/wiki/Java_%28programming_language%29" rel="nofollow noreferrer">Java</a> enum, that\'s how I do it in Python:</p>\n\n<pre><code>def enum(clsdef):\n    class Enum(object):\n        __slots__=tuple([var for var in clsdef.__dict__ if isinstance((getattr(clsdef, var)), tuple) and not var.startswith(\'__\')])\n\n        def __new__(cls, *args, **kwargs):\n            if not \'_the_instance\' in cls.__dict__:\n                cls._the_instance = object.__new__(cls, *args, **kwargs)\n            return cls._the_instance\n\n        def __init__(self):\n            clsdef.values=lambda cls, e=Enum: e.values()\n            clsdef.valueOf=lambda cls, n, e=self: e.valueOf(n)\n            for ordinal, key in enumerate(self.__class__.__slots__):\n                args=getattr(clsdef, key)\n                instance=clsdef(*args)\n                instance._name=key\n                instance._ordinal=ordinal\n                setattr(self, key, instance)\n\n        @classmethod\n        def values(cls):\n            if not hasattr(cls, \'_values\'):\n                cls._values=[getattr(cls, name) for name in cls.__slots__]\n            return cls._values\n\n        def valueOf(self, name):\n            return getattr(self, name)\n\n        def __repr__(self):\n            return \'\'.join([\'&lt;class Enum (\', clsdef.__name__, \') at \', str(hex(id(self))), \'&gt;\'])\n\n    return Enum()\n</code></pre>\n\n<p>Sample use:</p>\n\n<pre><code>i=2\n@enum\nclass Test(object):\n    A=("a",1)\n    B=("b",)\n    C=("c",2)\n    D=tuple()\n    E=("e",3)\n\n    while True:\n        try:\n            F, G, H, I, J, K, L, M, N, O=[tuple() for _ in range(i)]\n            break;\n        except ValueError:\n            i+=1\n\n    def __init__(self, name="default", aparam=0):\n        self.name=name\n        self.avalue=aparam\n</code></pre>\n\n<p>All class variables are defined as a tuple, just like the constructor. So far, you can\'t use named arguments.</p>\n'}, {'answer_id': 4092436, 'author': 'royal', 'author_id': 133934, 'author_profile': 'https://Stackoverflow.com/users/133934', 'pm_score': 6, 'selected': False, 'text': "<p>So, I agree. Let's not enforce type safety in Python, but I would like to protect myself from silly mistakes. So what do we think about this?</p>\n\n<pre><code>class Animal(object):\n    values = ['Horse','Dog','Cat']\n\n    class __metaclass__(type):\n        def __getattr__(self, name):\n            return self.values.index(name)\n</code></pre>\n\n<p>It keeps me from value-collision in defining my enums.</p>\n\n<pre><code>&gt;&gt;&gt; Animal.Cat\n2\n</code></pre>\n\n<p>There's another handy advantage: really fast reverse lookups:</p>\n\n<pre><code>def name_of(self, i):\n    return self.values[i]\n</code></pre>\n"}, {'answer_id': 4300343, 'author': 'mbac32768', 'author_id': 18446, 'author_profile': 'https://Stackoverflow.com/users/18446', 'pm_score': 5, 'selected': False, 'text': "<p>I prefer to define enums in Python like so:</p>\n<pre><code>class Animal:\n  class Dog: pass\n  class Cat: pass\n\nx = Animal.Dog\n</code></pre>\n<p>It's more bug-proof than using integers since you don't have to worry about ensuring that the integers are unique (e.g. if you said Dog = 1 and Cat = 1 you'd be screwed).</p>\n<p>It's more bug-proof than using strings since you don't have to worry about typos (e.g.\nx == &quot;catt&quot; fails silently, but x == Animal.Catt is a runtime exception).</p>\n<hr />\n<p>ADDENDUM :\nYou can even enhance this solution by having Dog and Cat inherit from a symbol class with the right metaclass :</p>\n<pre><code>class SymbolClass(type):\n    def __repr__(self): return self.__qualname__\n    def __str__(self): return self.__name__\n\nclass Symbol(metaclass=SymbolClass): pass\n\n\nclass Animal:\n    class Dog(Symbol): pass\n    class Cat(Symbol): pass\n</code></pre>\n<p>Then, if you use those values to e.g. index a dictionary, Requesting it's representation will make them appear nicely:</p>\n<pre><code>&gt;&gt;&gt; mydict = {Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa'}\n&gt;&gt;&gt; mydict\n{Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa'}\n</code></pre>\n"}, {'answer_id': 6347576, 'author': 'Roy Hyunjin Han', 'author_id': 192092, 'author_profile': 'https://Stackoverflow.com/users/192092', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a variant on <a href="https://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python/1695250#1695250">Alec Thomas\'s solution</a>:</p>\n\n<pre><code>def enum(*args, **kwargs):\n    return type(\'Enum\', (), dict((y, x) for x, y in enumerate(args), **kwargs)) \n\nx = enum(\'POOH\', \'TIGGER\', \'EEYORE\', \'ROO\', \'PIGLET\', \'RABBIT\', \'OWL\')\nassert x.POOH == 0\nassert x.TIGGER == 1\n</code></pre>\n'}, {'answer_id': 6971002, 'author': 'agf', 'author_id': 500584, 'author_profile': 'https://Stackoverflow.com/users/500584', 'pm_score': 5, 'selected': False, 'text': '<p>Another, very simple, implementation of an enum in Python, using <code>namedtuple</code>:</p>\n<pre><code>from collections import namedtuple\n\ndef enum(*keys):\n    return namedtuple(\'Enum\', keys)(*keys)\n\nMyEnum = enum(\'FOO\', \'BAR\', \'BAZ\')\n</code></pre>\n<p>or, alternatively,</p>\n<pre class="lang-py prettyprint-override"><code># With sequential number values\ndef enum(*keys):\n    return namedtuple(\'Enum\', keys)(*range(len(keys)))\n\n# From a dict / keyword args\ndef enum(**kwargs):\n    return namedtuple(\'Enum\', kwargs.keys())(*kwargs.values())\n\n\n\n\n# Example for dictionary param:\nvalues = {&quot;Salad&quot;: 20, &quot;Carrot&quot;: 99, &quot;Tomato&quot;: &quot;No i\'m not&quot;} \nVegetables= enum(**values)\n\n# &gt;&gt;&gt; print(Vegetables.Tomato)        \'No i\'m not\'\n\n\n# Example for keyworded params: \nFruits = enum(Apple=&quot;Steve Jobs&quot;, Peach=1, Banana=2)\n\n# &gt;&gt;&gt; print(Fruits.Apple)             \'Steve Jobs\'\n</code></pre>\n<p>Like the method above that subclasses <code>set</code>, this allows:</p>\n<pre><code>\'FOO\' in MyEnum\nother = MyEnum.FOO\nassert other == MyEnum.FOO\n</code></pre>\n<p>But has more flexibility as it can have different keys and values. This allows</p>\n<pre><code>MyEnum.FOO &lt; MyEnum.BAR\n</code></pre>\n<p>to act as is expected if you use the version that fills in sequential number values.</p>\n'}, {'answer_id': 7458935, 'author': 'Michael Truog', 'author_id': 950809, 'author_profile': 'https://Stackoverflow.com/users/950809', 'pm_score': 2, 'selected': False, 'text': "<p>This solution is a simple way of getting a class for the enumeration defined as a list (no more annoying integer assignments):</p>\n\n<p>enumeration.py:</p>\n\n<pre><code>import new\n\ndef create(class_name, names):\n    return new.classobj(\n        class_name, (object,), dict((y, x) for x, y in enumerate(names))\n    )\n</code></pre>\n\n<p>example.py:</p>\n\n<pre><code>import enumeration\n\nColors = enumeration.create('Colors', (\n    'red',\n    'orange',\n    'yellow',\n    'green',\n    'blue',\n    'violet',\n))\n</code></pre>\n"}, {'answer_id': 8598742, 'author': 'SingleNegationElimination', 'author_id': 65696, 'author_profile': 'https://Stackoverflow.com/users/65696', 'pm_score': 4, 'selected': False, 'text': '<p>I have had occasion to need of an Enum class, for the purpose of decoding a binary file format. The features I happened to want is concise enum definition, the ability to freely create instances of the enum by either integer value or string, and a useful <code>repr</code>esentation.  Here\'s what I ended up with:</p>\n\n<pre><code>&gt;&gt;&gt; class Enum(int):\n...     def __new__(cls, value):\n...         if isinstance(value, str):\n...             return getattr(cls, value)\n...         elif isinstance(value, int):\n...             return cls.__index[value]\n...     def __str__(self): return self.__name\n...     def __repr__(self): return "%s.%s" % (type(self).__name__, self.__name)\n...     class __metaclass__(type):\n...         def __new__(mcls, name, bases, attrs):\n...             attrs[\'__slots__\'] = [\'_Enum__name\']\n...             cls = type.__new__(mcls, name, bases, attrs)\n...             cls._Enum__index = _index = {}\n...             for base in reversed(bases):\n...                 if hasattr(base, \'_Enum__index\'):\n...                     _index.update(base._Enum__index)\n...             # create all of the instances of the new class\n...             for attr in attrs.keys():\n...                 value = attrs[attr]\n...                 if isinstance(value, int):\n...                     evalue = int.__new__(cls, value)\n...                     evalue._Enum__name = attr\n...                     _index[value] = evalue\n...                     setattr(cls, attr, evalue)\n...             return cls\n... \n</code></pre>\n\n<p>A whimsical example of using it:</p>\n\n<pre><code>&gt;&gt;&gt; class Citrus(Enum):\n...     Lemon = 1\n...     Lime = 2\n... \n&gt;&gt;&gt; Citrus.Lemon\nCitrus.Lemon\n&gt;&gt;&gt; \n&gt;&gt;&gt; Citrus(1)\nCitrus.Lemon\n&gt;&gt;&gt; Citrus(5)\nTraceback (most recent call last):\n  File "&lt;stdin&gt;", line 1, in &lt;module&gt;\n  File "&lt;stdin&gt;", line 6, in __new__\nKeyError: 5\n&gt;&gt;&gt; class Fruit(Citrus):\n...     Apple = 3\n...     Banana = 4\n... \n&gt;&gt;&gt; Fruit.Apple\nFruit.Apple\n&gt;&gt;&gt; Fruit.Lemon\nCitrus.Lemon\n&gt;&gt;&gt; Fruit(1)\nCitrus.Lemon\n&gt;&gt;&gt; Fruit(3)\nFruit.Apple\n&gt;&gt;&gt; "%d %s %r" % ((Fruit.Apple,)*3)\n\'3 Apple Fruit.Apple\'\n&gt;&gt;&gt; Fruit(1) is Citrus.Lemon\nTrue\n</code></pre>\n\n<p>Key features:</p>\n\n<ul>\n<li><code>str()</code>, <code>int()</code> and <code>repr()</code> all produce the most useful output possible, respectively the name of the enumartion, its integer value, and a Python expression that evaluates back to the enumeration.</li>\n<li>Enumerated values returned by the constructor are limited strictly to the predefined values, no accidental enum values.</li>\n<li>Enumerated values are singletons; they can be strictly compared with <code>is</code></li>\n</ul>\n'}, {'answer_id': 8905914, 'author': 'bj0', 'author_id': 618895, 'author_profile': 'https://Stackoverflow.com/users/618895', 'pm_score': 4, 'selected': False, 'text': '<p>I really like Alec Thomas\' solution (http://stackoverflow.com/a/1695250):</p>\n\n<pre><code>def enum(**enums):\n    \'\'\'simple constant "enums"\'\'\'\n    return type(\'Enum\', (object,), enums)\n</code></pre>\n\n<p>It\'s elegant and clean looking, but it\'s just a function that creates a class with the specified attributes.</p>\n\n<p>With a little modification to the function, we can get it to act a little more \'enumy\':</p>\n\n<blockquote>\n  <p>NOTE: I created the following examples by trying to reproduce the\n  behavior of pygtk\'s new style \'enums\' (like Gtk.MessageType.WARNING)</p>\n</blockquote>\n\n<pre><code>def enum_base(t, **enums):\n    \'\'\'enums with a base class\'\'\'\n    T = type(\'Enum\', (t,), {})\n    for key,val in enums.items():\n        setattr(T, key, T(val))\n\n    return T\n</code></pre>\n\n<p>This creates an enum based off a specified type. In addition to giving attribute access like the previous function, it behaves as you would expect an Enum to with respect to types.  It also inherits the base class.</p>\n\n<p>For example, integer enums:</p>\n\n<pre><code>&gt;&gt;&gt; Numbers = enum_base(int, ONE=1, TWO=2, THREE=3)\n&gt;&gt;&gt; Numbers.ONE\n1\n&gt;&gt;&gt; x = Numbers.TWO\n&gt;&gt;&gt; 10 + x\n12\n&gt;&gt;&gt; type(Numbers)\n&lt;type \'type\'&gt;\n&gt;&gt;&gt; type(Numbers.ONE)\n&lt;class \'Enum\'&gt;\n&gt;&gt;&gt; isinstance(x, Numbers)\nTrue\n</code></pre>\n\n<p>Another interesting thing that can be done with this method is customize specific behavior by overriding built-in methods:</p>\n\n<pre><code>def enum_repr(t, **enums):\n    \'\'\'enums with a base class and repr() output\'\'\'\n    class Enum(t):\n        def __repr__(self):\n            return \'&lt;enum {0} of type Enum({1})&gt;\'.format(self._name, t.__name__)\n\n    for key,val in enums.items():\n        i = Enum(val)\n        i._name = key\n        setattr(Enum, key, i)\n\n    return Enum\n\n\n\n&gt;&gt;&gt; Numbers = enum_repr(int, ONE=1, TWO=2, THREE=3)\n&gt;&gt;&gt; repr(Numbers.ONE)\n\'&lt;enum ONE of type Enum(int)&gt;\'\n&gt;&gt;&gt; str(Numbers.ONE)\n\'1\'\n</code></pre>\n'}, {'answer_id': 9201329, 'author': 'Zoetic', 'author_id': 653048, 'author_profile': 'https://Stackoverflow.com/users/653048', 'pm_score': 6, 'selected': False, 'text': "<p>An Enum class can be a one-liner.</p>\n\n<pre><code>class Enum(tuple): __getattr__ = tuple.index\n</code></pre>\n\n<p>How to use it (forward and reverse lookup, keys, values, items, etc.)</p>\n\n<pre><code>&gt;&gt;&gt; State = Enum(['Unclaimed', 'Claimed'])\n&gt;&gt;&gt; State.Claimed\n1\n&gt;&gt;&gt; State[1]\n'Claimed'\n&gt;&gt;&gt; State\n('Unclaimed', 'Claimed')\n&gt;&gt;&gt; range(len(State))\n[0, 1]\n&gt;&gt;&gt; [(k, State[k]) for k in range(len(State))]\n[(0, 'Unclaimed'), (1, 'Claimed')]\n&gt;&gt;&gt; [(k, getattr(State, k)) for k in State]\n[('Unclaimed', 0), ('Claimed', 1)]\n</code></pre>\n"}, {'answer_id': 10004274, 'author': 'jianpx', 'author_id': 544251, 'author_profile': 'https://Stackoverflow.com/users/544251', 'pm_score': 2, 'selected': False, 'text': '<p>I use a metaclass to implement an enumeration (in my thought, it is a const). Here is the code:</p>\n\n<pre><code>class ConstMeta(type):\n    \'\'\'\n    Metaclass for some class that store constants\n    \'\'\'\n    def __init__(cls, name, bases, dct):\n        \'\'\'\n        init class instance\n        \'\'\'\n        def static_attrs():\n            \'\'\'\n            @rtype: (static_attrs, static_val_set)\n            @return: Static attributes in dict format and static value set\n            \'\'\'\n            import types\n            attrs = {}\n            val_set = set()\n            #Maybe more\n            filter_names = set([\'__doc__\', \'__init__\', \'__metaclass__\', \'__module__\', \'__main__\'])\n            for key, value in dct.iteritems():\n                if type(value) != types.FunctionType and key not in filter_names:\n                    if len(value) != 2:\n                        raise NotImplementedError(\'not support for values that is not 2 elements!\')\n                    #Check value[0] duplication.\n                    if value[0] not in val_set:\n                        val_set.add(value[0])\n                    else:\n                        raise KeyError("%s \'s key: %s is duplicated!" % (dict([(key, value)]), value[0]))\n                    attrs[key] = value\n            return attrs, val_set\n\n        attrs, val_set = static_attrs()\n        #Set STATIC_ATTRS to class instance so that can reuse\n        setattr(cls, \'STATIC_ATTRS\', attrs)\n        setattr(cls, \'static_val_set\', val_set)\n        super(ConstMeta, cls).__init__(name, bases, dct)\n\n    def __getattribute__(cls, name):\n        \'\'\'\n        Rewrite the special function so as to get correct attribute value\n        \'\'\'\n        static_attrs = object.__getattribute__(cls, \'STATIC_ATTRS\')\n        if name in static_attrs:\n            return static_attrs[name][0]\n        return object.__getattribute__(cls, name)\n\n    def static_values(cls):\n        \'\'\'\n        Put values in static attribute into a list, use the function to validate value.\n        @return: Set of values\n        \'\'\'\n        return cls.static_val_set\n\n    def __getitem__(cls, key):\n        \'\'\'\n        Rewrite to make syntax SomeConstClass[key] works, and return desc string of related static value.\n        @return: Desc string of related static value\n        \'\'\'\n        for k, v in cls.STATIC_ATTRS.iteritems():\n            if v[0] == key:\n                return v[1]\n        raise KeyError(\'Key: %s does not exists in %s !\' % (str(key), repr(cls)))\n\n\nclass Const(object):\n    \'\'\'\n    Base class for constant class.\n\n    @usage:\n\n    Definition: (must inherit from Const class!\n        &gt;&gt;&gt; class SomeConst(Const):\n        &gt;&gt;&gt;   STATUS_NAME_1 = (1, \'desc for the status1\')\n        &gt;&gt;&gt;   STATUS_NAME_2 = (2, \'desc for the status2\')\n\n    Invoke(base upper SomeConst class):\n    1) SomeConst.STATUS_NAME_1 returns 1\n    2) SomeConst[1] returns \'desc for the status1\'\n    3) SomeConst.STATIC_ATTRS returns {\'STATUS_NAME_1\': (1, \'desc for the status1\'), \'STATUS_NAME_2\': (2, \'desc for the status2\')}\n    4) SomeConst.static_values() returns set([1, 2])\n\n    Attention:\n    SomeCosnt\'s value 1, 2 can not be duplicated!\n    If WrongConst is like this, it will raise KeyError:\n    class WrongConst(Const):\n        STATUS_NAME_1 = (1, \'desc for the status1\')\n        STATUS_NAME_2 = (1, \'desc for the status2\')\n    \'\'\'\n    __metaclass__ = ConstMeta\n##################################################################\n#Const Base Class ends\n##################################################################\n\n\ndef main():\n    class STATUS(Const):\n        ERROR = (-3, \'??\')\n        OK = (0, \'??\')\n\n    print STATUS.ERROR\n    print STATUS.static_values()\n    print STATUS.STATIC_ATTRS\n\n    #Usage sample:\n    user_input = 1\n    #Validate input:\n    print user_input in STATUS.static_values()\n    #Template render like:\n    print \'&lt;select&gt;\'\n    for key, value in STATUS.STATIC_ATTRS.items():\n        print \'&lt;option value="%s"&gt;%s&lt;/option&gt;\' % (value[0], value[1])\n    print \'&lt;/select&gt;\'\n\n\nif __name__ == \'__main__\':\n    main()\n</code></pre>\n'}, {'answer_id': 11147900, 'author': 'Oxdeadbeef', 'author_id': 545299, 'author_profile': 'https://Stackoverflow.com/users/545299', 'pm_score': 2, 'selected': False, 'text': '<p>A variant (with support to get an enum value\'s name) to <a href="https://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python/1695250#1695250">Alec Thomas\'s neat answer</a>:</p>\n\n<pre><code>class EnumBase(type):\n    def __init__(self, name, base, fields):\n        super(EnumBase, self).__init__(name, base, fields)\n        self.__mapping = dict((v, k) for k, v in fields.iteritems())\n    def __getitem__(self, val):\n        return self.__mapping[val]\n\ndef enum(*seq, **named):\n    enums = dict(zip(seq, range(len(seq))), **named)\n    return EnumBase(\'Enum\', (), enums)\n\nNumbers = enum(ONE=1, TWO=2, THREE=\'three\')\nprint Numbers.TWO\nprint Numbers[Numbers.ONE]\nprint Numbers[2]\nprint Numbers[\'three\']\n</code></pre>\n'}, {'answer_id': 13474078, 'author': 'Jah', 'author_id': 1207615, 'author_profile': 'https://Stackoverflow.com/users/1207615', 'pm_score': 2, 'selected': False, 'text': "<p>I like to use lists or sets as enumerations. For example:</p>\n\n<pre><code>&gt;&gt;&gt; packet_types = ['INIT', 'FINI', 'RECV', 'SEND']\n&gt;&gt;&gt; packet_types.index('INIT')\n0\n&gt;&gt;&gt; packet_types.index('FINI')\n1\n&gt;&gt;&gt;\n</code></pre>\n"}, {'answer_id': 14628126, 'author': 'Noctis Skytower', 'author_id': 216356, 'author_profile': 'https://Stackoverflow.com/users/216356', 'pm_score': 2, 'selected': False, 'text': '<p>The solution that I usually use is this simple function to get an instance of a dynamically created class.</p>\n\n<pre><code>def enum(names):\n    "Create a simple enumeration having similarities to C."\n    return type(\'enum\', (), dict(map(reversed, enumerate(\n        names.replace(\',\', \' \').split())), __slots__=()))()\n</code></pre>\n\n<p>Using it is as simple as calling the function with a string having the names that you want to reference.</p>\n\n<pre><code>grade = enum(\'A B C D F\')\nstate = enum(\'awake, sleeping, dead\')\n</code></pre>\n\n<p>The values are just integers, so you can take advantage of that if desired (just like in the C language).</p>\n\n<pre><code>&gt;&gt;&gt; grade.A\n0\n&gt;&gt;&gt; grade.B\n1\n&gt;&gt;&gt; grade.F == 4\nTrue\n&gt;&gt;&gt; state.dead == 2\nTrue\n</code></pre>\n'}, {'answer_id': 15886819, 'author': 'FDS', 'author_id': 823602, 'author_profile': 'https://Stackoverflow.com/users/823602', 'pm_score': 2, 'selected': False, 'text': '<h2>Python 2.7 and find_name()</h2>\n\n<p>Here is an easy-to-read implementation of the chosen idea with some helper methods, which perhaps are more Pythonic and cleaner to use than "reverse_mapping". Requires Python >= 2.7. </p>\n\n<p>To address some comments below, Enums are quite useful to prevent spelling mistakes in code, e.g. for state machines, error classifiers, etc.</p>\n\n<pre><code>def Enum(*sequential, **named):\n  """Generate a new enum type. Usage example:\n\n  ErrorClass = Enum(\'STOP\',\'GO\')\n  print ErrorClass.find_name(ErrorClass.STOP)\n    = "STOP"\n  print ErrorClass.find_val("STOP")\n    = 0\n  ErrorClass.FOO     # Raises AttributeError\n  """\n  enums = { v:k for k,v in enumerate(sequential) } if not named else named\n\n  @classmethod\n  def find_name(cls, val):\n    result = [ k for k,v in cls.__dict__.iteritems() if v == val ]\n    if not len(result):\n        raise ValueError("Value %s not found in Enum" % val)\n    return result[0]\n\n  @classmethod\n  def find_val(cls, n):\n    return getattr(cls, n)\n\n  enums[\'find_val\'] = find_val\n  enums[\'find_name\'] = find_name\n  return type(\'Enum\', (), enums)\n</code></pre>\n'}, {'answer_id': 16095707, 'author': 'abarnert', 'author_id': 908494, 'author_profile': 'https://Stackoverflow.com/users/908494', 'pm_score': 3, 'selected': False, 'text': '<p>While the original enum proposal, <a href="http://www.python.org/dev/peps/pep-0354/" rel="nofollow">PEP 354</a>, was rejected years ago, it keeps coming back up. Some kind of enum was intended to be added to 3.2, but it got pushed back to 3.3 and then forgotten. And now there\'s a <a href="http://www.python.org/dev/peps/pep-0435/" rel="nofollow">PEP 435</a> intended for inclusion in Python 3.4. The reference implementation of PEP 435 is <a href="http://pythonhosted.org/flufl.enum/docs/using.html" rel="nofollow"><code>flufl.enum</code></a>.</p>\n\n<p>As of April 2013, there seems to be a general consensus that <em>something</em> should be added to the standard library in 3.4—as long as people can agree on what that "something" should be. That\'s the hard part. See the threads starting <a href="http://mail.python.org/pipermail/python-ideas/2013-January/019003.html" rel="nofollow">here</a> and <a href="http://mail.python.org/pipermail/python-ideas/2013-February/019332.html" rel="nofollow">here</a>, and a half dozen other threads in the early months of 2013.</p>\n\n<p>Meanwhile, every time this comes up, a slew of new designs and implementations appear on PyPI, ActiveState, etc., so if you don\'t like the FLUFL design, try a <a href="https://pypi.python.org/pypi?%3aaction=search&amp;term=enum&amp;submit=search" rel="nofollow">PyPI search</a>.</p>\n'}, {'answer_id': 16486444, 'author': 'Danilo Bargen', 'author_id': 284318, 'author_profile': 'https://Stackoverflow.com/users/284318', 'pm_score': 5, 'selected': False, 'text': '<p>On 2013-05-10, Guido agreed to accept <a href="http://www.python.org/dev/peps/pep-0435/">PEP 435</a> into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!</p>\n\n<p>There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4.  It\'s on Pypi as <a href="https://pypi.python.org/pypi/enum34">enum34</a>.</p>\n\n<p>Declaration:</p>\n\n<pre><code>&gt;&gt;&gt; from enum import Enum\n&gt;&gt;&gt; class Color(Enum):\n...     red = 1\n...     green = 2\n...     blue = 3\n</code></pre>\n\n<p>Representation:</p>\n\n<pre><code>&gt;&gt;&gt; print(Color.red)\nColor.red\n&gt;&gt;&gt; print(repr(Color.red))\n&lt;Color.red: 1&gt;\n</code></pre>\n\n<p>Iteration:</p>\n\n<pre><code>&gt;&gt;&gt; for color in Color:\n...   print(color)\n...\nColor.red\nColor.green\nColor.blue\n</code></pre>\n\n<p>Programmatic access:</p>\n\n<pre><code>&gt;&gt;&gt; Color(1)\nColor.red\n&gt;&gt;&gt; Color[\'blue\']\nColor.blue\n</code></pre>\n\n<p>For more information, refer to <a href="http://www.python.org/dev/peps/pep-0435/">the proposal</a>. Official documentation will probably follow soon.</p>\n'}, {'answer_id': 16486681, 'author': 'Riaz Rizvi', 'author_id': 213307, 'author_profile': 'https://Stackoverflow.com/users/213307', 'pm_score': 4, 'selected': False, 'text': '<p>The standard in Python is <a href="http://www.python.org/dev/peps/pep-0435/" rel="nofollow noreferrer">PEP 435</a>, so an Enum class is available in Python 3.4+:</p>\n<pre><code>&gt;&gt;&gt; from enum import Enum\n&gt;&gt;&gt; class Colors(Enum):\n...     red = 1\n...     green = 2\n...     blue = 3\n&gt;&gt;&gt; for color in Colors: print color\nColors.red\nColors.green\nColors.blue\n</code></pre>\n'}, {'answer_id': 17201727, 'author': 'Chris Johnson', 'author_id': 763269, 'author_profile': 'https://Stackoverflow.com/users/763269', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s an approach with some different characteristics I find valuable:</p>\n\n<ul>\n<li>allows > and &lt; comparison based on order in enum, not lexical order</li>\n<li>can address item by name, property or index: x.a, x[\'a\'] or x[0]</li>\n<li>supports slicing operations like [:] or [-1]</li>\n</ul>\n\n<p>and most importantly <strong>prevents comparisons between enums of different types</strong>!</p>\n\n<p>Based closely on <a href="http://code.activestate.com/recipes/413486-first-class-enums-in-python" rel="noreferrer">http://code.activestate.com/recipes/413486-first-class-enums-in-python</a>.</p>\n\n<p>Many doctests included here to illustrate what\'s different about this approach.</p>\n\n<pre><code>def enum(*names):\n    """\nSYNOPSIS\n    Well-behaved enumerated type, easier than creating custom classes\n\nDESCRIPTION\n    Create a custom type that implements an enumeration.  Similar in concept\n    to a C enum but with some additional capabilities and protections.  See\n    http://code.activestate.com/recipes/413486-first-class-enums-in-python/.\n\nPARAMETERS\n    names       Ordered list of names.  The order in which names are given\n                will be the sort order in the enum type.  Duplicate names\n                are not allowed.  Unicode names are mapped to ASCII.\n\nRETURNS\n    Object of type enum, with the input names and the enumerated values.\n\nEXAMPLES\n    &gt;&gt;&gt; letters = enum(\'a\',\'e\',\'i\',\'o\',\'u\',\'b\',\'c\',\'y\',\'z\')\n    &gt;&gt;&gt; letters.a &lt; letters.e\n    True\n\n    ## index by property\n    &gt;&gt;&gt; letters.a\n    a\n\n    ## index by position\n    &gt;&gt;&gt; letters[0]\n    a\n\n    ## index by name, helpful for bridging string inputs to enum\n    &gt;&gt;&gt; letters[\'a\']\n    a\n\n    ## sorting by order in the enum() create, not character value\n    &gt;&gt;&gt; letters.u &lt; letters.b\n    True\n\n    ## normal slicing operations available\n    &gt;&gt;&gt; letters[-1]\n    z\n\n    ## error since there are not 100 items in enum\n    &gt;&gt;&gt; letters[99]\n    Traceback (most recent call last):\n        ...\n    IndexError: tuple index out of range\n\n    ## error since name does not exist in enum\n    &gt;&gt;&gt; letters[\'ggg\']\n    Traceback (most recent call last):\n        ...\n    ValueError: tuple.index(x): x not in tuple\n\n    ## enums must be named using valid Python identifiers\n    &gt;&gt;&gt; numbers = enum(1,2,3,4)\n    Traceback (most recent call last):\n        ...\n    AssertionError: Enum values must be string or unicode\n\n    &gt;&gt;&gt; a = enum(\'-a\',\'-b\')\n    Traceback (most recent call last):\n        ...\n    TypeError: Error when calling the metaclass bases\n        __slots__ must be identifiers\n\n    ## create another enum\n    &gt;&gt;&gt; tags = enum(\'a\',\'b\',\'c\')\n    &gt;&gt;&gt; tags.a\n    a\n    &gt;&gt;&gt; letters.a\n    a\n\n    ## can\'t compare values from different enums\n    &gt;&gt;&gt; letters.a == tags.a\n    Traceback (most recent call last):\n        ...\n    AssertionError: Only values from the same enum are comparable\n\n    &gt;&gt;&gt; letters.a &lt; tags.a\n    Traceback (most recent call last):\n        ...\n    AssertionError: Only values from the same enum are comparable\n\n    ## can\'t update enum after create\n    &gt;&gt;&gt; letters.a = \'x\'\n    Traceback (most recent call last):\n        ...\n    AttributeError: \'EnumClass\' object attribute \'a\' is read-only\n\n    ## can\'t update enum after create\n    &gt;&gt;&gt; del letters.u\n    Traceback (most recent call last):\n        ...\n    AttributeError: \'EnumClass\' object attribute \'u\' is read-only\n\n    ## can\'t have non-unique enum values\n    &gt;&gt;&gt; x = enum(\'a\',\'b\',\'c\',\'a\')\n    Traceback (most recent call last):\n        ...\n    AssertionError: Enums must not repeat values\n\n    ## can\'t have zero enum values\n    &gt;&gt;&gt; x = enum()\n    Traceback (most recent call last):\n        ...\n    AssertionError: Empty enums are not supported\n\n    ## can\'t have enum values that look like special function names\n    ## since these could collide and lead to non-obvious errors\n    &gt;&gt;&gt; x = enum(\'a\',\'b\',\'c\',\'__cmp__\')\n    Traceback (most recent call last):\n        ...\n    AssertionError: Enum values beginning with __ are not supported\n\nLIMITATIONS\n    Enum values of unicode type are not preserved, mapped to ASCII instead.\n\n    """\n    ## must have at least one enum value\n    assert names, \'Empty enums are not supported\'\n    ## enum values must be strings\n    assert len([i for i in names if not isinstance(i, types.StringTypes) and not \\\n        isinstance(i, unicode)]) == 0, \'Enum values must be string or unicode\'\n    ## enum values must not collide with special function names\n    assert len([i for i in names if i.startswith("__")]) == 0,\\\n        \'Enum values beginning with __ are not supported\'\n    ## each enum value must be unique from all others\n    assert names == uniquify(names), \'Enums must not repeat values\'\n\n    class EnumClass(object):\n        """ See parent function for explanation """\n\n        __slots__ = names\n\n        def __iter__(self):\n            return iter(constants)\n\n        def __len__(self):\n            return len(constants)\n\n        def __getitem__(self, i):\n            ## this makes xx[\'name\'] possible\n            if isinstance(i, types.StringTypes):\n                i = names.index(i)\n            ## handles the more normal xx[0]\n            return constants[i]\n\n        def __repr__(self):\n            return \'enum\' + str(names)\n\n        def __str__(self):\n            return \'enum \' + str(constants)\n\n        def index(self, i):\n            return names.index(i)\n\n    class EnumValue(object):\n        """ See parent function for explanation """\n\n        __slots__ = (\'__value\')\n\n        def __init__(self, value):\n            self.__value = value\n\n        value = property(lambda self: self.__value)\n\n        enumtype = property(lambda self: enumtype)\n\n        def __hash__(self):\n            return hash(self.__value)\n\n        def __cmp__(self, other):\n            assert self.enumtype is other.enumtype, \'Only values from the same enum are comparable\'\n            return cmp(self.value, other.value)\n\n        def __invert__(self):\n            return constants[maximum - self.value]\n\n        def __nonzero__(self):\n            ## return bool(self.value)\n            ## Original code led to bool(x[0])==False, not correct\n            return True\n\n        def __repr__(self):\n            return str(names[self.value])\n\n    maximum = len(names) - 1\n    constants = [None] * len(names)\n    for i, each in enumerate(names):\n        val = EnumValue(i)\n        setattr(EnumClass, each, val)\n        constants[i] = val\n    constants = tuple(constants)\n    enumtype = EnumClass()\n    return enumtype\n</code></pre>\n'}, {'answer_id': 18627613, 'author': 'David', 'author_id': 926217, 'author_profile': 'https://Stackoverflow.com/users/926217', 'pm_score': 2, 'selected': False, 'text': '<p>Didn\'t see this one in the list of answers, here is the one I whipped up. It allows the use of \'in\' keyword and len() method:</p>\n\n<pre><code>class EnumTypeError(TypeError):\n    pass\n\nclass Enum(object):\n    """\n    Minics enum type from different languages\n    Usage:\n    Letters = Enum(list(\'abc\'))\n    a = Letters.a\n    print(a in Letters) # True\n    print(54 in Letters) # False\n    """\n    def __init__(self, enums):\n        if isinstance(enums, dict):\n            self.__dict__.update(enums)\n        elif isinstance(enums, list) or isinstance(enums, tuple):\n            self.__dict__.update(**dict((v,k) for k,v in enumerate(enums)))\n        else:\n            raise EnumTypeError\n\n    def __contains__(self, key):\n        return key in self.__dict__.values()\n\n    def __len__(self):\n        return len(self.__dict__.values())\n\n\nif __name__ == \'__main__\':\n    print(\'Using a dictionary to create Enum:\')\n    Letters = Enum(dict((v,k) for k,v in enumerate(list(\'abcde\'))))\n    a = Letters.a\n    print(\'\\tIs a in e?\', a in Letters)\n    print(\'\\tIs 54 in e?\', 54 in Letters)\n    print(\'\\tLength of Letters enum:\', len(Letters))\n\n    print(\'\\nUsing a list to create Enum:\')\n    Letters = Enum(list(\'abcde\'))\n    a = Letters.a\n    print(\'\\tIs a in e?\', a in Letters)\n    print(\'\\tIs 54 in e?\', 54 in Letters)\n    print(\'\\tLength of Letters enum:\', len(Letters))\n\n    try:\n        # make sure we raise an exception if we pass an invalid arg\n        Failure = Enum(\'This is a Failure\')\n        print(\'Failure\')\n    except EnumTypeError:\n        print(\'Success!\')\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Using a dictionary to create Enum:\n        Is a in e? True\n        Is 54 in e? False\n        Length of Letters enum: 5\n\nUsing a list to create Enum:\n        Is a in e? True\n        Is 54 in e? False\n        Length of Letters enum: 5\nSuccess!\n</code></pre>\n'}, {'answer_id': 20520884, 'author': 'Saša Šijak', 'author_id': 257501, 'author_profile': 'https://Stackoverflow.com/users/257501', 'pm_score': 5, 'selected': False, 'text': '<p>From Python 3.4 there is official support for enums. You can find documentation and examples <a href="http://docs.python.org/3.4/library/enum.html" rel="nofollow noreferrer">here on Python 3.4 documentation page</a>.</p>\n<blockquote>\n<p>Enumerations are created using the class syntax, which makes them easy\nto read and write. An alternative creation method is described in\nFunctional API. To define an enumeration, subclass Enum as follows:</p>\n</blockquote>\n<pre><code>from enum import Enum\nclass Color(Enum):\n     red = 1\n     green = 2\n     blue = 3\n</code></pre>\n'}, {'answer_id': 22461315, 'author': 'Rafay', 'author_id': 569085, 'author_profile': 'https://Stackoverflow.com/users/569085', 'pm_score': 3, 'selected': False, 'text': '<p>Here is a nice Python recipe that I found here: <a href="http://code.activestate.com/recipes/577024-yet-another-enum-for-python/" rel="nofollow">http://code.activestate.com/recipes/577024-yet-another-enum-for-python/</a></p>\n\n<pre><code>def enum(typename, field_names):\n    "Create a new enumeration type"\n\n    if isinstance(field_names, str):\n        field_names = field_names.replace(\',\', \' \').split()\n    d = dict((reversed(nv) for nv in enumerate(field_names)), __slots__ = ())\n    return type(typename, (object,), d)()\n</code></pre>\n\n<p>Example Usage:</p>\n\n<pre><code>STATE = enum(\'STATE\', \'GET_QUIZ, GET_VERSE, TEACH\')\n</code></pre>\n\n<p>More details can be found on the recipe page.</p>\n'}, {'answer_id': 22723724, 'author': 'Melroy van den Berg', 'author_id': 518879, 'author_profile': 'https://Stackoverflow.com/users/518879', 'pm_score': 5, 'selected': False, 'text': '<p>Keep it simple, using old Python 2.x (see below for Python 3!):</p>\n<pre><code>class Enum(object): \n    def __init__(self, tupleList):\n            self.tupleList = tupleList\n    \n    def __getattr__(self, name):\n            return self.tupleList.index(name)\n</code></pre>\n<p>Then:</p>\n<pre><code>DIRECTION = Enum((\'UP\', \'DOWN\', \'LEFT\', \'RIGHT\'))\nDIRECTION.DOWN\n1\n</code></pre>\n<hr />\n<p>Keep it simple when using <strong>Python 3</strong>:</p>\n<pre><code>from enum import Enum\nclass MyEnum(Enum):\n    UP = 1\n    DOWN = 2\n    LEFT = 3\n    RIGHT = 4\n</code></pre>\n<p>Then:</p>\n<pre><code>MyEnum.DOWN\n</code></pre>\n<p>See: <a href="https://docs.python.org/3/library/enum.html" rel="noreferrer">https://docs.python.org/3/library/enum.html</a></p>\n'}, {'answer_id': 26861507, 'author': 'estani', 'author_id': 1182464, 'author_profile': 'https://Stackoverflow.com/users/1182464', 'pm_score': 4, 'selected': False, 'text': "<p>For old Python 2.x</p>\n<pre><code>def enum(*sequential, **named):\n    enums = dict(zip(sequential, [object() for _ in range(len(sequential))]), **named)\n    return type('Enum', (), enums)\n</code></pre>\n<p>If you name it, is your problem, but if not creating objects instead of values allows you to do this:</p>\n<pre><code>&gt;&gt;&gt; DOG = enum('BARK', 'WALK', 'SIT')\n&gt;&gt;&gt; CAT = enum('MEOW', 'WALK', 'SIT')\n&gt;&gt;&gt; DOG.WALK == CAT.WALK\nFalse\n</code></pre>\n<p>When using other implementations sited here (also when using named instances in my example) you must be sure you never try to compare objects from different enums. For here's a possible pitfall:</p>\n<pre><code>&gt;&gt;&gt; DOG = enum('BARK'=1, 'WALK'=2, 'SIT'=3)\n&gt;&gt;&gt; CAT = enum('WALK'=1, 'SIT'=2)\n&gt;&gt;&gt; pet1_state = DOG.BARK\n&gt;&gt;&gt; pet2_state = CAT.WALK\n&gt;&gt;&gt; pet1_state == pet2_state\nTrue\n</code></pre>\n<p>Yikes!</p>\n"}]
['https://Stackoverflow.com/questions/36932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3880/']