How can I represent an 'Enum' in Python?
<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>

<p>Enums have been added to Python 3.4 as described in <a href="http://www.python.org/dev/peps/pep-0435/" rel="nofollow">PEP 435</a>.  It has also been <a href="https://pypi.python.org/pypi/enum34" rel="nofollow">backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4</a> on pypi.  </p>

<p>For more advanced Enum techniques try the <a href="https://pypi.python.org/pypi/aenum" rel="nofollow">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="http://stackoverflow.com/a/25982264/57461"><code>__order__</code> in python 2</a>).</p>

<ul>
<li>To use <code>enum34</code>, do <code>$ pip install enum34</code></li>
<li>To use <code>aenum</code>, do <code>$ pip install aenum</code></li>
</ul>

<p>Installing <code>enum</code> (no numbers) will install a completely different and incompatible version.</p>

<hr>

<pre><code>from enum import Enum     # for enum34, or the stdlib version
# from aenum import Enum  # for the aenum version
Animal = Enum('Animal', 'ant bee cat dog')

Animal.ant  # returns &lt;Animal.ant: 1&gt;
Animal['ant']  # returns &lt;Animal.ant: 1&gt; (string lookup)
Animal.ant.name  # returns 'ant' (inverse lookup)
</code></pre>

<p>or equivalently:</p>

<pre><code>class Animal(Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4
</code></pre>

<hr>

<p>In earlier versions, one way of accomplishing enums is:</p>

<pre><code>def enum(**enums):
    return type('Enum', (), enums)
</code></pre>

<p>which is used like so:</p>

<pre><code>&gt;&gt;&gt; Numbers = enum(ONE=1, TWO=2, THREE='three')
&gt;&gt;&gt; Numbers.ONE
1
&gt;&gt;&gt; Numbers.TWO
2
&gt;&gt;&gt; Numbers.THREE
'three'
</code></pre>

<p>You can also easily support automatic enumeration with something like this:</p>

<pre><code>def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)
</code></pre>

<p>and used like so:</p>

<pre><code>&gt;&gt;&gt; Numbers = enum('ZERO', 'ONE', 'TWO')
&gt;&gt;&gt; Numbers.ZERO
0
&gt;&gt;&gt; Numbers.ONE
1
</code></pre>

<p>Support for converting the values back to names can be added this way:</p>

<pre><code>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)
</code></pre>

<p>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:</p>

<pre><code>&gt;&gt;&gt; Numbers.reverse_mapping['three']
'THREE'
</code></pre>
