Recipes

All of the following are published as "public domain", or, if you prefer, under the MIT license. Some of my older recipes can be found on the Python Cookbook

Property Classes May 14, 2011 Tired of creating properties the old way? Python 3 brings an improvement in the form of multi-stage properties, i.e., @property def foo(self): ... # getter @foo.setter def foo(self, value): ... # setter It still feels very awkward. I can't say my solution is pure elegance, but I find it cleaner.... »»»
ctypes - Pointer from Address April 27, 2011 There are times you need to construct a ctypes pointer from an integer address you have, say the id of a python object. I scratched my head for quite a while until I found out a how to do it properly (with some help from the stackoverflow guys). Here's what... »»»
Copy Function Defaults February 06, 2007 Default arguments to functions are evaluated when the function is created, and are stored in the function object. This cause irritating problems when the default values are in fact mutable, as only single instance exists: >>> def f(x = []): ... x.append(5) ... print x ... >>> f() [5] >>>... »»»
Weak Methods September 29, 2006 Many times you would pass bound methods to other functions, as callbacks (i.e., to simulate events, etc.). However, bound methods (the instancemethod type) hold a strong reference to their owning instance (im_self), which means the existence of a bound method is enough to hold the instance "alive", even though your... »»»
Real Mixins September 22, 2006 The normal python paradigm for implementing mixins is using multiple inheritance. Mixin classes take some measures of precaution as of their design (not to interfere with the derivee's MRO as much as possible), but they are essentially just regular classes, being derived from. This code here creates real mixed-in classes:... »»»
Hooking dir() September 07, 2006 While working with proxy objects I found introspection quite hard, as the mechanism of dir() just looks at the object's __dict__ (with some exceptions), and there's no way to customize this introspection. But do not fear, hacking skillz are near! After reading into the machinery of dir(), I found a... »»»
Module Mixins a la Ruby August 29, 2006 Multiple inheritance is usually considered bad, and many ways to avoid it have been developed. The first and most notable is interfaces, which are basically abstract classes (only declaration, no implementation). Another solution is mix-in classes, which add functionality ("implementation") to the class, but do not affect the inheritance tree.... »»»
Killable Threads August 13, 2006 The thread2 module is an extension of the standard threading module, and provides the means to raise exceptions at the context of the given thread. You can use raise_exc() to raise an arbitrary exception, or call terminate() to raise SystemExit automatically. It uses the unexposed PyThreadState_SetAsyncExc function (via ctypes) to... »»»
HTML Codec July 26, 2006 A very simple and straight-forward text/HTML codec. When encoding text, it escapes all HTML-delimiters (< becomes &lt;, etc.), so the encoded text can be safely viewed by an HTML renderer (browser) or safely embedded into an HTML document. When decoding HTML, it unescapes the formatters into plain text (so that... »»»
Weak Attributes June 04, 2006 Weak attributes are attributes of an instance that hold only a weak reference to another object. They are very useful for automatic breaking of cyclic references. This weakattr class implements a data-descriptor that holds a weak reference to the attribute, so that when it's no longer strongly-referenced, it automatically "disappears"... »»»
SeqAttr June 03, 2006 Sequenced attributes are useful for types that behave as sequences, but provide direct attribute access. For examples of such types, see time.struct_time of the result of os.fstat. Note: since the inclusion of namedtuple, this recipe is considered deprecated. ==Code== class seqattr(object): __slots__ = ["index"] def __init__(self, index): self.index= index def... »»»
HElement May 30, 2006 HElement, or HTML-element, is a simple, straight-forward, and non-magical HTML generation engine. An HElement is made of two parts: attrs - the attributes of the tag, and elems - the sub-elements of the tag. Sub-elements can be either HElements by themselves, or plain objects whose str() is used to embed... »»»
AttrDict May 29, 2006 A dictionary that can be accessed with the attribute notation, as well as the item notation: using AttrDict, a.b is the same as a["b"]. Also, iterating over an AttrDict yields (key, value) pairs (instead of only keys, as in dicts). Note, however, that because of the unification of getattr and... »»»
ExceptionContainer May 28, 2006 An exception baseclass inspired by Container, which takes keyword arguments instead of positional ones, and provides pretty-printing in tracebacks. Code # # module ExceptionContainer.py # requires the Container module # from Container import Container class ExceptionContainer(Exception): def __init__(self, message = "", **kw): self.__dict__["__info"] = Container(message = message, **kw) def __delattr__(self,... »»»
Container May 27, 2006 A general container of attributes, with support for pretty printing. Very useful for debugging, etc. Used extensively in Construct to represent parsed objects. Code # # module Container.py # def recursion_lock(retval, lock_name = "____recursion_lock"): def decorator(func): def wrapper(self, *args, **kw): if getattr(self, lock_name, False): return retval setattr(self, lock_name, True) try:... »»»
Templite May 26, 2006 Templite is a fast, light-weight, general purpose, and fully featured templating engine in ~40 lines of code. Unlike many templating engines, this one is not specific to any format (HTML, XML, etc.). Instead, all the text surrounded by ${ and }$ is evaluated as python code. Any python code can... »»»