Latest recipes by Eric Snow http://code.activestate.com/recipes/users/4177816/new/2013-03-08T17:00:53-08:00ActiveState Code RecipesClass-only Methods (Python) 2013-03-08T17:00:53-08:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578486-class-only-methods/ <p style="color: grey"> Python recipe 578486 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/metaprogramming/">metaprogramming</a>). </p> <p>We use the classmethod builtin to tie methods to the class rather than the instance. This is really useful for a variety of things, like alternate contructors. However, sometimes you don't want to expose the method on the instances, just on the class.</p> <p>For instance, it usually doesn't make a lot of sense to have direct access to alternate constructors from instances; the main constructor, via the __call__ method, is only available on the class. Why? So that instances call implement their own call semantics. This is similar to why the methods (and other class attributes) on namedtuples all have names starting with an underscore.</p> <p>To restrict a method just to the class, currently you must use a metaclass. Most people consider this black magic so they just use @classmethod. Furthermore, implementing a metaclass is simply more verbose than decorating a method with classmethod. Plus you have to deal with things like metaclass conflicts and the fact that metaclasses are inherited.</p> <p>So...here is a sibling to classmethod that makes a method class-only without introducing metaclass complexity. You use it the same way as you would classmethod.</p> A Class Decorator that Adds a copy() Method (Python) 2013-02-14T20:43:20-08:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578457-a-class-decorator-that-adds-a-copy-method/ <p style="color: grey"> Python recipe 578457 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/metaprogramming/">metaprogramming</a>). </p> <p>Here's a class decorator that adds a rudimentary copy() method onto the decorated class. Use it like this:</p> <pre class="prettyprint"><code>@copiable class SomethingDifferent: def __init__(self, a, b, c): self.a = a self.b = b self.c = c </code></pre> <p>or like this:</p> <pre class="prettyprint"><code>@copiable("a b c") class SomethingDifferent: def __init__(self, a, b, c): self.a = a self.b = b self.c = c s = SomethingDifferent(1,2,3) sc = s.copy() assert vars(s) == vars(sc) </code></pre> <p>(Python 3.3)</p> A class decorator for creating named tuples (Python) 2013-02-14T19:58:13-08:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578456-a-class-decorator-for-creating-named-tuples/ <p style="color: grey"> Python recipe 578456 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/metaprogramming/">metaprogramming</a>, <a href="/recipes/tags/namedtuple/">namedtuple</a>). Revision 3. </p> <p>This class decorator factory is useful for replacing the following:</p> <pre class="prettyprint"><code>class MyTuple(namedtuple('MyTuple', "a b c")): """Something special.""" @classmethod def from_defaults(cls, a, b=None, c=5): return cls(a, b, c) </code></pre> <p>or even:</p> <pre class="prettyprint"><code>class MyTuple(namedtuple('MyTuple', "a b c")): """Something special.""" def __new__(cls, a, b=None, c=5): return super().__new__(cls, a, b, c) </code></pre> <p>with this:</p> <pre class="prettyprint"><code>@as_namedtuple("a b c", None, c=5) class MyTuple: """Something special.""" </code></pre> <p>I found that I often subclass named tuples to add on some functionality or even just a nice docstring. Plus with the class syntax there's no missing that a class is bound to the name (and it's a little easier to search for the definition). When you subclass a named tuple the boilerplate involved really jumps out.</p> <p>One of the main reasons Adding support for defaults to namedtuple would mitigate the need for that functionality here, but I'm not going to hold my breath on that.</p> <p>One nice (though minor) thing is that you don't have to repeat the name when defining the namedtuple.</p> A simple enum type (Python) 2013-02-13T06:53:38-08:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578455-a-simple-enum-type/ <p style="color: grey"> Python recipe 578455 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/enum/">enum</a>, <a href="/recipes/tags/metaclass/">metaclass</a>). Revision 2. </p> <p>Inspired by various threads[1] on the python-ideas list, here's a simple enum type. Enums are generated either via the class syntax or via Enum.make().</p> <pre class="prettyprint"><code>class Breakfast(Enum): SPAM, HAM, EGGS BACON, SAUSAGE Breakfast = Enum.make("SPAM HAM EGGS BACON SAUSAGE") </code></pre> <p>Here are some of the features:</p> <p>Enum:</p> <ul> <li>inheriting from an enum inherits copies of its values.</li> <li>the export() method allows for exposing an enum's values in another namespace.</li> </ul> <p>Enum Values:</p> <ul> <li>the underlying values within an enum are essentially useless, diminishing the temptation to rely on them.</li> <li>identity is equality, like with None, True, and False.</li> <li>enum values support bitwise operations within the same enum.</li> <li>the result of a bitwise operation is always the same object given the same inputs.</li> </ul> <p>[1] see <a href="http://mail.python.org/pipermail/python-ideas/2013-January/019003.html" rel="nofollow">http://mail.python.org/pipermail/python-ideas/2013-January/019003.html</a></p> ChainedList and ChainedListView: Exposing Multiple Lists as a Single Sequence (Python) 2012-07-03T21:00:02-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578190-chainedlist-and-chainedlistview-exposing-multiple-/ <p style="color: grey"> Python recipe 578190 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/lists/">lists</a>, <a href="/recipes/tags/wrapper/">wrapper</a>). </p> <p>Handy for composing lists without losing the underlying indepedence. The "lists" don't actually have to be lists, though for ChainedList they must be mutable.</p> A generic factory factory. (Python) 2012-06-11T23:31:11-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578165-a-generic-factory-factory/ <p style="color: grey"> Python recipe 578165 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/factory/">factory</a>). </p> <p>Factories are useful for producing objects without having to store certain data on the objects' type. Instances of this factory class are factories that can produce </p> A Simpler Namespace Class (Python) 2013-02-14T17:42:24-08:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578141-a-simpler-namespace-class/ <p style="color: grey"> Python recipe 578141 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/namespaces/">namespaces</a>, <a href="/recipes/tags/object/">object</a>). Revision 3. </p> <p>A very simple, attribute-based namespace type (and one offspring). Everyone's written one of these...</p> Tracking and Manipulating the Python Import State (Python) 2012-04-22T07:27:29-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578107-tracking-and-manipulating-the-python-import-state/ <p style="color: grey"> Python recipe 578107 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/import/">import</a>). </p> <p>This is a rough analog to the import engine described in PEP 406. Here I've called it ImportState.The focus here is on using it as a context manager to limit changes to the import state to a block of code (in a with statement). Differences from PEP 406 are described below.</p> A MutableMapping that Can Use Unhashable Objects as Keys (Python) 2012-04-04T20:36:59-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578096-a-mutablemapping-that-can-use-unhashable-objects-a/ <p style="color: grey"> Python recipe 578096 by <a href="/recipes/users/4177816/">Eric Snow</a> . </p> <p>The catch is that the unhashable objects aren't actually stored in the mapping. Only their IDs are. Thus you must also store the actual objects somewhere else.</p> A Script that Adds a Directory to sys.path Permanently (Python) 2012-02-16T23:15:11-08:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578043-a-script-that-adds-a-directory-to-syspath-permanen/ <p style="color: grey"> Python recipe 578043 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/script/">script</a>, <a href="/recipes/tags/sys_path/">sys_path</a>). </p> <p>This script takes advantage of PEP 370, "Per user site-packages directory". It manages .pth files, which are are non-volatile (unlike manually adding to sys.path). See <a href="http://docs.python.org/library/site.html." rel="nofollow">http://docs.python.org/library/site.html.</a></p> Emulate Keyword-Only Arguments in Python 2 (Python) 2011-11-03T18:31:52-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577940-emulate-keyword-only-arguments-in-python-2/ <p style="color: grey"> Python recipe 577940 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/argument/">argument</a>, <a href="/recipes/tags/keyword_only/">keyword_only</a>, <a href="/recipes/tags/kwonly/">kwonly</a>, <a href="/recipes/tags/parameter/">parameter</a>). </p> <p>Python 3 introduced a useful feature: keyword-only arguments. In order to get the same effect in Python 2, you must use **kwargs in your parameter list. Then, at the beginning of your function body you must manually extract what would be the keyword-only arguments once you upgrade to 3.</p> <p>This recipe helps reduce the boilerplate to a single function call. You still don't get those parameters in your "def" clause (where they are more obvious), but at least it reduces the clutter.</p> Simple Lock Classes Based on threading.Lock() (Python) 2011-10-19T21:26:39-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577914-simple-lock-classes-based-on-threadinglock/ <p style="color: grey"> Python recipe 577914 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/lock/">lock</a>, <a href="/recipes/tags/locking/">locking</a>). </p> <p>Nothing fancy here. Locks can take many forms. Here are a few.</p> A Protocol for Making Objects Immutable (Python) 2011-10-07T03:59:45-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577895-a-protocol-for-making-objects-immutable/ <p style="color: grey"> Python recipe 577895 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/freeze/">freeze</a>, <a href="/recipes/tags/immutable/">immutable</a>, <a href="/recipes/tags/mutable/">mutable</a>, <a href="/recipes/tags/unfreeze/">unfreeze</a>). </p> <p>Python already provides immutable versions of many of the mutable built-in types. Dict is the notable exception. Regardless, here is a protocol that objects may implement that facilitates turning immutable object mutable and vice-versa.</p> See What the Builtins Are (Python) 2011-11-04T22:44:09-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577888-see-what-the-builtins-are/ <p style="color: grey"> Python recipe 577888 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/builtins/">builtins</a>). Revision 3. </p> <p>The built-ins are all those functions, constants, and types that are there when you need them most, like <code>list</code>, <code>any</code>, and <code>None</code>. This recipe is a simple way of looking at the built-ins. Check below for a thorough explanation.</p> A Simple Namespace Class (Python) 2011-10-03T21:12:41-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577887-a-simple-namespace-class/ <p style="color: grey"> Python recipe 577887 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/dict/">dict</a>, <a href="/recipes/tags/namespaces/">namespaces</a>). Revision 3. </p> <p>"Namespaces are one honking great idea -- let's do more of those!" -- <a href="http://www.python.org/dev/peps/pep-0020/">The Zen of Python</a></p> <p>For when you want a simple, easy namespace, but you don't want it cluttered up with Python's object machinery.</p> Inspect a PYC File (Python) 2011-09-29T20:07:10-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577880-inspect-a-pyc-file/ <p style="color: grey"> Python recipe 577880 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/bytecode/">bytecode</a>, <a href="/recipes/tags/inspection/">inspection</a>, <a href="/recipes/tags/pyc/">pyc</a>). Revision 3. </p> <p>This is a revamp of a recipe that Ned Batchelder <a href="http://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html">posted on his blog</a> a few years ago (thanks Ned!). That page is pretty insightful, recipe aside.</p> <p>This recipe works for all versions of Python back to 2.4 (at least). Warning: using one version of Python to inspect a pyc file from another Python version may not work too well.</p> Make a Class Available in its Own Definition Body! (Python) 2011-09-15T05:36:36-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577867-make-a-class-available-in-its-own-definition-body/ <p style="color: grey"> Python recipe 577867 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/metaclass/">metaclass</a>). </p> <p>This may sound too good to be true, but see for yourself. No time machines involved. Just plug in this metaclass and look for __newclass__ in your class body. It's not perfect, but the problematic corner cases are more bark than bite.</p> Mixins by Inheritance vs. by Decorator...Let's Try Decorators (Python) 2011-08-12T15:29:21-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577824-mixins-by-inheritance-vs-by-decoratorlets-try-deco/ <p style="color: grey"> Python recipe 577824 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/mixins/">mixins</a>). </p> <p>Using mixin classes via inheritance has its pros and cons. Here is an easy alternative via a decorator. As a bonus, you can mix in attributes from any object, not just classes.</p> Turn a Function Into a Class (Python) 2011-10-05T18:38:43-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577822-turn-a-function-into-a-class/ <p style="color: grey"> Python recipe 577822 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/classes/">classes</a>, <a href="/recipes/tags/functions/">functions</a>). </p> <p>The only catch is that the function has to return locals() at the end. And it doesn't do the __prepare__ part of 3.x metaclasses.</p> Turn @some_decorator() into @some_decorator (Python) 2011-08-04T18:48:36-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577820-turn-some_decorator-into-some_decorator/ <p style="color: grey"> Python recipe 577820 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/decorators/">decorators</a>). </p> <p>A decorator factory is a function that returns a decorator based on the arguments you pass in. Sometimes you make a decorator factory to cover uncommon use cases. In that case you'll probably use default arguments to cover your common case.</p> <p>The problem with this, however, is that you still have to use the call syntax (with no arguments) to get the common-use-case decorator, as demonstrated in the recipe title. This recipe effectively makes it so that your decorator factory and your common-use-case decorator have the same name (and actually the same object).</p>