Latest recipes tagged "metaprogramming"http://code.activestate.com/recipes/tags/metaprogramming/new/2014-07-24T04:25:53-07:00ActiveState Code RecipesPython AsciiColor and video attributes (Python)
2014-07-24T04:25:53-07:00Mike 'Fuzzy' Partinhttp://code.activestate.com/recipes/users/4179778/http://code.activestate.com/recipes/578908-python-asciicolor-and-video-attributes/
<p style="color: grey">
Python
recipe 578908
by <a href="/recipes/users/4179778/">Mike 'Fuzzy' Partin</a>
(<a href="/recipes/tags/ascii/">ascii</a>, <a href="/recipes/tags/color/">color</a>, <a href="/recipes/tags/dynamic_method/">dynamic_method</a>, <a href="/recipes/tags/metaprogramming/">metaprogramming</a>, <a href="/recipes/tags/python/">python</a>).
Revision 5.
</p>
<p>This is a subclass of a standard str object that adds methods for applying color, and video attributes to text.</p>
Class-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>
Object snoop - experiment with Python special methods (Python)
2010-09-05T17:54:50-07:00Wai Yip Tunghttp://code.activestate.com/recipes/users/2382677/http://code.activestate.com/recipes/577383-object-snoop-experiment-with-python-special-method/
<p style="color: grey">
Python
recipe 577383
by <a href="/recipes/users/2382677/">Wai Yip Tung</a>
(<a href="/recipes/tags/metaprogramming/">metaprogramming</a>, <a href="/recipes/tags/methods/">methods</a>, <a href="/recipes/tags/object/">object</a>).
</p>
<p>In Python, classes can define their own behavior with respect to language operators. For example, if a class defines __getitem__(), then x[i], where x is an instance of the clas, will be execute by a call to x.__getitem__(i).</p>
<p>While Python has an extensive documentation on the special methods, reading a specification may not be the best way to reveal the intricate details. <strong>object_snoop</strong> allows user to observe how Python expressions and statements are translated into special method calls. object_snoop defines most special methods. It simple print a trace and returns a fixed but sensible result. Users are invited to build complex expressions to experiment how Python special methods work.</p>
Docstring inheritance decorator (Python)
2009-07-28T13:42:32-07:00Shai Bergerhttp://code.activestate.com/recipes/users/2014324/http://code.activestate.com/recipes/576862-docstring-inheritance-decorator/
<p style="color: grey">
Python
recipe 576862
by <a href="/recipes/users/2014324/">Shai Berger</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/descriptor/">descriptor</a>, <a href="/recipes/tags/docstring/">docstring</a>, <a href="/recipes/tags/inheritance/">inheritance</a>, <a href="/recipes/tags/metaprogramming/">metaprogramming</a>).
</p>
<p>In many cases, a subclass overrides a method in a parent class, just to change its implementation; in such cases, it would be nice to preserve the overridden method's docstring. The decorator below can be used to achieve this without explicit reference to the parent class. It does this by replacing the function with a descriptor, which accesses the parent class when the method is accessed as an attribute.</p>
Subclass function (Python)
2009-03-23T00:48:54-07:00Peter Russellhttp://code.activestate.com/recipes/users/4166045/http://code.activestate.com/recipes/576697-subclass-function/
<p style="color: grey">
Python
recipe 576697
by <a href="/recipes/users/4166045/">Peter Russell</a>
(<a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/metaprogramming/">metaprogramming</a>, <a href="/recipes/tags/subclass/">subclass</a>).
Revision 4.
</p>
<p><strong>Do not use this function - instead use the built in type(name, bases, dict) constructor</strong> This is a function that builds a subclass of some base classes. I wrote it while unaware that type could be used as a constructor.</p>