Top-rated recipes tagged "chainmap"http://code.activestate.com/recipes/tags/chainmap/top/2012-10-03T18:12:50-07:00ActiveState Code RecipesUsing ChainMap for embedded namespaces (Python) 2012-10-03T18:12:50-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/578279-using-chainmap-for-embedded-namespaces/ <p style="color: grey"> Python recipe 578279 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/chainmap/">chainmap</a>, <a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/namespace/">namespace</a>). </p> <p>The Zen of Python tells us:</p> <p><em>Namespaces are one honking great idea -- let's do more of those!</em></p> <p>Python already has an excellent namespace type, the module, but the problem with modules is that they have to live in a separate file, and sometimes you want the convenience of a single file while still encapsulating your code into namespaces. That's where classes are the usual solution, but classes need to be instantiated and methods need to be defined with a <code>self</code> parameter.</p> <p>C++ has "namespaces" for encapsulating related objects and dividing the global scope into sub-scopes. Can we do the same in Python?</p> <p>With a bit of metaclass trickery and the new ChainMap type from Python 3.3, we can!</p>