Top-rated recipes tagged "duckpunching"http://code.activestate.com/recipes/tags/duckpunching/top/2012-10-18T19:41:22-07:00ActiveState Code RecipesPython Immutable Enumerations Using Duck Punching (Python)
2012-10-18T19:41:22-07:00Josh Friendhttp://code.activestate.com/recipes/users/4183977/http://code.activestate.com/recipes/578294-python-immutable-enumerations-using-duck-punching/
<p style="color: grey">
Python
recipe 578294
by <a href="/recipes/users/4183977/">Josh Friend</a>
(<a href="/recipes/tags/duckpunching/">duckpunching</a>, <a href="/recipes/tags/enum/">enum</a>, <a href="/recipes/tags/enumeration/">enumeration</a>, <a href="/recipes/tags/monkeypatching/">monkeypatching</a>, <a href="/recipes/tags/python/">python</a>).
</p>
<p>Here's a fun method of creating enumerations in Python using dynamic class creation and duck-punching (monkey-patching). It works by creating a class called <code>enum</code> using the <code>type</code> metaclass. Duck-punching is then used to add properties to the class. the <code>fget</code> method of the property returns the enum value, but the <code>fset</code> and <code>fdel</code> methods throw exceptions, keeping the enumeration immutable. You can have enum values assigned automatically in sequence, assign them yourself, or have a mix of both.</p>