Python, what's the Enum type good for?
<p>In Python 3.4, we got an Enum lib in the standard library: <code>enum</code>. We can get a backport for <code>enum</code> that works with Python 2.4 to 2.7 (and even 3.1 to 3.3), <a href="https://pypi.python.org/pypi/enum34" rel="noreferrer">enum34</a> in pypi.</p>

<p>But we've managed to get along for quite some time without this new module - so why do we now have it?</p>

<p>I have a general idea about the purpose of enums from other languages. In Python, it has been common to use a bare class as follows and refer to this as an enum:</p>

<pre><code>class Colors:
    blue = 1
    green = 2
    red = 3
</code></pre>

<p>This can be used in an API to create a canonical representation of the value, e.g.:</p>

<pre><code>function_of_color(Colors.green)
</code></pre>

<p>If this has any criticisms, it's mutable, you can't iterate over it (easily), and how are we to know the semantics of the integer, <code>2</code>?</p>

<p>Then I suppose I could just use something like a namedtuple, which would be immutable?</p>

<pre><code>&gt;&gt;&gt; Colors = namedtuple('Colors', 'blue green red')
&gt;&gt;&gt; colors = Colors('blue', 'green', 'red')
&gt;&gt;&gt; colors
Colors(blue='blue', green='green', red='red')
&gt;&gt;&gt; list(colors)
['blue', 'green', 'red']
&gt;&gt;&gt; len(colors)
3
&gt;&gt;&gt; colors.blue
'blue'
&gt;&gt;&gt; colors.index(colors.blue)
0
</code></pre>

<p>The creation of the namedtuple is a little redundant (we have to write each name twice), and so somewhat inelegant. Getting the "number" of the color is also a little inelegant (we have to write <code>colors</code> twice). Value checking will have to be done with strings, which will be a little less efficient.</p>

<p>So back to enums.</p>

<p>What's the purpose of enums? What value do they create for the language? When should I use them and when should I avoid them?</p>