Python: Make a dynamically created class (as in the class itself) iterable?
<p>I started with this code snippet, which, by my understanding, is essentially a class-factory of sorts to emulate an "enum" type from other languages:</p>

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

<p>(which I took from here: <a href="http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python">What&#39;s the best way to implement an &#39;enum&#39; in Python?</a> )</p>

<p>I get how it works, and it does, but I would like to make my dynamically generated classes, which are of type 'Enum', iterable so that i can do the following in order to do a sanity check:</p>

<pre><code>MyEnum = enum('FOO', 'BAR', 'JIMMY')
def func(my_enum_value):  # expects one of the MyEnum values
    if not my_enum_value in MyEnum:
        raise SomeSortOfException
</code></pre>

<p>However, in order to make that sanity check work, I need to make MyEnum iterable. I read here: <a href="http://pydanny.blogspot.com/2007/10/required-methods-to-make-class-iterable.html" rel="nofollow">http://pydanny.blogspot.com/2007/10/required-methods-to-make-class-iterable.html</a> that  I needed to add <strong>iter</strong> _<em>len</em>_ <strong>contains</strong> and <strong>getitem</strong> methods to something in order to make it iterable. I started down this road (rewriting the enum code) but got stuck:</p>

<pre><code>def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    enums['_enums'] = enums.copy() # (so I'd have them in the Class in order to use for the methods I'll be implementing to make it iterable)
    Enum = type('Enum', (), enums)

    Enum.__iter__ = #Er, how do I do this? Guess I'll ask SO
    Enum.__len__ =  # etc. 
    # . . . 
    return Enum
</code></pre>

<p>SO, how do I make my generated Enum classes iterable so I can use the 'in' word with them? This isn't life or death for me, but I'm learning a ton of Python by doing this.</p>

<p>Thanks,</p>

<p>Ben </p>
