Popular Python recipes tagged "monkeypatching"http://code.activestate.com/recipes/langs/python/tags/monkeypatching/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> Dynamically modifying class attributes at runtime (Python) 2011-03-31T20:07:18-07:00Nabil Stendardohttp://code.activestate.com/recipes/users/4177507/http://code.activestate.com/recipes/577628-dynamically-modifying-class-attributes-at-runtime/ <p style="color: grey"> Python recipe 577628 by <a href="/recipes/users/4177507/">Nabil Stendardo</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/modification/">modification</a>, <a href="/recipes/tags/monkeypatching/">monkeypatching</a>, <a href="/recipes/tags/open/">open</a>). </p> <p>However considered bad programming, Ruby/JavaScript-like open classes (i.e. classes which can be modified at runtime) actually can be a programming pattern when developing plug-in architectures. And, guess what, Python has that functionality too. This code allows to add attributes (typically methods) to classes, even when already instantiated.</p>