py3k feature proposal: field auto-assignment in constructors
André
andre.roberge at gmail.com
Mon Jan 28 11:08:18 EST 2008
On Jan 28, 11:45 am, Steven Bethard <steven.beth... at gmail.com> wrote:
> 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
If I may suggest, I would extend this so that autoassign's signature
would be as follows:
autoassign(all=True, include_only=None, exclude=None)
Either one of include_only or exclude could be a list of function to
which the automatic assignment would apply (or not). I was planning
to write this up and submit it to the cookbook later this evening, but
since the suggestion has been made, someone else can jump on it. ;-)
André
More information about the Python-list
mailing list