[Python-ideas] a few decorator recipes

Mathias Panzenböck grosser.meister.morti at gmx.net
Fri Apr 29 19:33:01 CEST 2011


A few decorator recipes that might be worthwhile to add to functools:

A way to assign annotations to functions/classes:

def annotations(**annots):
	def deco(obj):
		if hasattr(obj,'__annotations__'):
			obj.__annotations__.update(annots)
		else:
			obj.__annotations__ = annots
		return obj
	return deco

_NONE = object()
def getannot(obj, key, default=_NONE):
	if hasattr(obj, '__annotations__'):
		if default is _NONE:
			return obj.__annotations__[key]
		else:
			return obj.__annotations__.get(key, default)
	elif default is _NONE:
		raise KeyError(key)
	else:
		return default

def setannot(obj, key, value):
	if hasattr(obj, '__annotations__'):
		obj.__annotations__[key] = value
	else:
		obj.__annotations__ = {key: value}

Usage:
 >>> @annotations(foo='bar',egg='spam')
 >>> def foo():
 >>> 	pass
 >>>
 >>> getannot(foo, 'egg')
'spam'


A way to assign values to classes/functions (not of much use for classes, of course):

def assign(**values):
	def deco(obj):
		for key in values:
			setattr(obj, key, values[key])
		return obj
	return deco

Usage:
 >>> @assign(bla='bleh',x=12)
 >>> def foo():
 >>> 	pass
 >>>
 >>> foo.x
12



More information about the Python-ideas mailing list