Arnaud Delobelle wrote: > Sligthly improved (not for performance! but signature-preserving and > looks for default values) > > from functools import wraps > from inspect import getargspec > from itertools import izip, chain > > def autoassign(*names): > def decorator(f): > fargnames, _, _, fdefaults = getargspec(f) > defaults = [(n,v) for (n,v) > in izip(reversed(fargnames), reversed(fdefaults)) > if n in names] > @wraps(f) > def decorated(self, *args, **kwargs): > self.__dict__.update(defaults) > for name, arg in chain(izip(fargnames, args), > kwargs.iteritems()): > if name in names: > setattr(self, name, arg) > return f(self, *args, **kwargs) > return decorated > return decorator > > class Test(object): > @autoassign('foo', 'bar') > def __init__(self, foo, bar=3, baz=6): > print 'baz =', baz > > t = Test(1, 2, 6) > u = Test(foo=8) > > print t.foo # 1 > print t.bar # 2 > > print u.foo # 8 > print u.bar # 3 (default)
You should definitely post this to the cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python STeVe -- http://mail.python.org/mailman/listinfo/python-list