Top-rated recipes tagged "metaclass"http://code.activestate.com/recipes/tags/metaclass/top/2016-07-31T04:03:29-07:00ActiveState Code Recipesargdeclare: declarative interface to argparse (Python)
2010-03-02T00:05:40-08:00Shakeeb Alirezahttp://code.activestate.com/recipes/users/4172101/http://code.activestate.com/recipes/576935-argdeclare-declarative-interface-to-argparse/
<p style="color: grey">
Python
recipe 576935
by <a href="/recipes/users/4172101/">Shakeeb Alireza</a>
(<a href="/recipes/tags/argparse/">argparse</a>, <a href="/recipes/tags/cmdln/">cmdln</a>, <a href="/recipes/tags/commandline/">commandline</a>, <a href="/recipes/tags/getopt/">getopt</a>, <a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/option/">option</a>).
Revision 5.
</p>
<p>This is an implementation of the interface provided by the <a href="http://code.google.com/p/cmdln/">cmdln</a> module but using <a href="http://code.google.com/p/argparse/">argparse</a> to provide the option/arg heavy parsing.</p>
<p>An example of usage is provided in the <code>test</code> function, which should produce the following from the command line:</p>
<p>$ python argdeclare.py --help</p>
<pre class="prettyprint"><code>usage: argdeclare.py [-h] [-v] {uninstall,install,delete} ...
a description of the test app
optional arguments:
-h, --help show this help message and exit
-v, --version show program's version number and exit
subcommands:
valid subcommands
{uninstall,install,delete}
additional help
delete help text for delete subcmd
install help text for install subcmd
uninstall help text for uninstall subcmd
</code></pre>
<p>$ python argdeclare.py install --help</p>
<pre class="prettyprint"><code>usage: argdeclare.py install [-h] [-t TYPE] [--log] [-f] package
positional arguments:
package package to be (un)installed
optional arguments:
-h, --help show this help message and exit
-t TYPE, --type TYPE specify type of package
--log, -l log is on
-f, --force force through installation
</code></pre>
<p>enjoy!</p>
<p>SA</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>
Emulating super() in Python 3.x using Python 2.7 (Python)
2016-07-31T04:03:29-07:00sunqingyaohttp://code.activestate.com/recipes/users/4194518/http://code.activestate.com/recipes/580694-emulating-super-in-python-3x-using-python-27/
<p style="color: grey">
Python
recipe 580694
by <a href="/recipes/users/4194518/">sunqingyao</a>
(<a href="/recipes/tags/beginner/">beginner</a>, <a href="/recipes/tags/descriptor/">descriptor</a>, <a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/oop/">oop</a>, <a href="/recipes/tags/python2/">python2</a>).
</p>
<p>Depending on the name of the first argument, <code>self.__sup</code> or <code>cls.__sup</code> behaves like <code>super()</code> in Python 3, while this code is written in Python 2.7.</p>
<p>It works for both ordinary methods and class methods(static methods don't use <code>super()</code>). See my code for detailed examples:</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>
Using 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>
A metaclass that hides details of the attribute name when called. (Python)
2012-08-31T09:53:59-07:00Chaobin Tang (唐超斌)http://code.activestate.com/recipes/users/4174076/http://code.activestate.com/recipes/578249-a-metaclass-that-hides-details-of-the-attribute-na/
<p style="color: grey">
Python
recipe 578249
by <a href="/recipes/users/4174076/">Chaobin Tang (唐超斌)</a>
(<a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/python/">python</a>).
Revision 2.
</p>
<p>In cases, where getting an attribute will
expose to the client code the detail of
the very attribute name, which could be changeable
over time.
This NamedAndCachedAttributeType is intended to
hide this detail by mapping the real attribute name
to another name that is maintained by the class itself.
By doing so, the content provider(this class) and the client
code(the caller) establish a deal that the changes of names
are taken care of by the provider itself.
Second, the value is set as a class variable once it is
first retreived, as being cached.</p>
METACLASS AND DEEPCOPY (Python)
2012-02-26T15:43:01-08:00thonpyhttp://code.activestate.com/recipes/users/4181053/http://code.activestate.com/recipes/578053-metaclass-and-deepcopy/
<p style="color: grey">
Python
recipe 578053
by <a href="/recipes/users/4181053/">thonpy</a>
(<a href="/recipes/tags/deepcopy/">deepcopy</a>, <a href="/recipes/tags/equal/">equal</a>, <a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/sign/">sign</a>).
</p>
<p>I would like to solve this excercise:
Traditionally object-oriented programming provides two different modes for cloning an instance or a structured data type: shallow and deep copy. The former has the effect to clone exclusively the external shell and not its content originating a quite fastidious aliasing effect. The latter, instead, copies the shell and its content recursively creating two completely separate copies of the instance.</p>
<p>As you know, Python's programs suffer of the aliasing effect when you copy an instance of a class or a structured type (e.g., a list) with the = operator. As showed in the following example:</p>
<p>l=[0,1,2]
mylist=l
mylist[2] = ’B’
mylist
[1, 2, ’B’]
l
[1, 2, ’B’</p>
<p>The exercise consists of defining a meta-class which implements the deep copy on the assignment operator and binding this to the standard class list. Such that the following behavior can be yielded</p>
Bunch class created from attributes in class (Python)
2011-12-31T18:03:02-08:00Fabio Zadroznyhttp://code.activestate.com/recipes/users/4180406/http://code.activestate.com/recipes/577999-bunch-class-created-from-attributes-in-class/
<p style="color: grey">
Python
recipe 577999
by <a href="/recipes/users/4180406/">Fabio Zadrozny</a>
(<a href="/recipes/tags/attributes/">attributes</a>, <a href="/recipes/tags/bunch/">bunch</a>, <a href="/recipes/tags/metaclass/">metaclass</a>).
Revision 3.
</p>
<p>Provide a way to construct class __init__, __slots__, __eq__, __ne__, __repr__ for the class and makes explicit which attributes each instance will have (and providing defaults).</p>
<p>The __main__ session shows an example of how it should be used.</p>
Make the New Class Available During the Execution of its Body (Python)
2011-08-12T23:44:46-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577744-make-the-new-class-available-during-the-execution-/
<p style="color: grey">
Python
recipe 577744
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>When a class object is created, normally the class body is exec'ed first and then the class object is generated with that resulting namespace. </p>
<p>This recipe lets you flip that around, and then make the class object available to the class body during execution. </p>
Using Metaclasses and Class Decorators to Inherit Function Docstrings (Python)
2011-06-11T00:59:35-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577743-using-metaclasses-and-class-decorators-to-inherit-/
<p style="color: grey">
Python
recipe 577743
by <a href="/recipes/users/4177816/">Eric Snow</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/docstring/">docstring</a>, <a href="/recipes/tags/inheritance/">inheritance</a>, <a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/metaclasses/">metaclasses</a>).
Revision 4.
</p>
<p>You'll find three different approaches to copying the method's docstring to the overriding method on a child class.</p>
<p>The function decorator approach is limited by the fact that you have to know the class when you call the decorator, so it can't be used inside a class body. However, <a href="http://code.activestate.com/recipes/577746/">recipe #577746</a> provides a function decorator that does not have this limitation.</p>
Auto Named Decriptors (Python)
2010-10-19T22:55:16-07:00Aloys Baillethttp://code.activestate.com/recipes/users/4175355/http://code.activestate.com/recipes/577426-auto-named-decriptors/
<p style="color: grey">
Python
recipe 577426
by <a href="/recipes/users/4175355/">Aloys Baillet</a>
(<a href="/recipes/tags/automatically/">automatically</a>, <a href="/recipes/tags/constants/">constants</a>, <a href="/recipes/tags/descriptors/">descriptors</a>, <a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/name/">name</a>, <a href="/recipes/tags/string/">string</a>).
Revision 3.
</p>
<p>Using named Descriptors? Tired of duplicating the name of the instance in a string? A small metaclass can solve this.</p>
Alias class attributes (Python)
2009-06-01T01:19:55-07:00Euan Goddardhttp://code.activestate.com/recipes/users/4170559/http://code.activestate.com/recipes/576787-alias-class-attributes/
<p style="color: grey">
Python
recipe 576787
by <a href="/recipes/users/4170559/">Euan Goddard</a>
(<a href="/recipes/tags/alias/">alias</a>, <a href="/recipes/tags/attribute/">attribute</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/descriptor/">descriptor</a>, <a href="/recipes/tags/metaclass/">metaclass</a>).
</p>
<p>The alias metaclass allows a declarative way of creating aliases to attributes on a class. The main purpose of which is to adapt classes for duck-typing (see doc-string for me detail).</p>
dynamically changing encoder (for json) with metaclass (class factory) (Python)
2013-10-24T11:31:44-07:00-http://code.activestate.com/recipes/users/4188267/http://code.activestate.com/recipes/578696-dynamically-changing-encoder-for-json-with-metacla/
<p style="color: grey">
Python
recipe 578696
by <a href="/recipes/users/4188267/">-</a>
(<a href="/recipes/tags/class_factory/">class_factory</a>, <a href="/recipes/tags/encode/">encode</a>, <a href="/recipes/tags/json/">json</a>, <a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/metaclasses/">metaclasses</a>).
</p>
<p>The <em>json.dumps</em> need to be feed with some class (cls =someClass) but what if we want to change the class dynamically?
This example can be done by declaring the <em>listOfClasses</em> in class level of course, but the idea is to be changeable. This can be done by the class factory function <em>encoderFacory</em></p>
threadbox.py (Python)
2012-10-09T22:40:09-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/578152-threadboxpy/
<p style="color: grey">
Python
recipe 578152
by <a href="/recipes/users/2608421/">Stephen Chappell</a>
(<a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/threading/">threading</a>).
Revision 2.
</p>
<p>Provide a way to run instance methods on a single thread.</p>
<p>This module allows hierarchical classes to be cloned so that their instances
run on one thread. Method calls are automatically routed through a special
execution engine. This is helpful when building thread-safe GUI code.</p>
Performance boost with metaclasses (Python)
2013-02-17T10:58:13-08:00Martin Schoepfhttp://code.activestate.com/recipes/users/4185283/http://code.activestate.com/recipes/578460-performance-boost-with-metaclasses/
<p style="color: grey">
Python
recipe 578460
by <a href="/recipes/users/4185283/">Martin Schoepf</a>
(<a href="/recipes/tags/metaclass/">metaclass</a>, <a href="/recipes/tags/performance/">performance</a>).
</p>
<p>Consider a highly dynamic system where a lot of objects are created and destroyed. If the objects are complex and have a lot of default values the following recipe may improve the performance. The more default values you have the more you will gain from it. </p>