Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code
Ralf W. Grosse-Kunstleve
rwgk at yahoo.com
Mon Jul 11 18:19:29 EDT 2005
--- Lonnie Princehouse <finite.automaton at gmail.com> wrote:
> IIRC, the self.__dict__.update(locals()) trick confuses psyco.
>
> But you can make a decorator to achieve the same result. There's not
> really a convincing case for extending python syntax.
Not if you have (enough memory for) psyco. :)
I am doing C++ extensions by hand; did quite a lot of them. Anything that helps
in pushing back the point where I have to move from Python to C++ is highly
appreciated. That's probably the strongest argument for the (self, self.x, ...)
approach. I believe it can be made more efficient than any other solution. But
see also the two other arguments:
http://mail.python.org/pipermail/python-list/2005-July/289721.html
> def attribute_decorator(f):
> import inspect
> argnames = inspect.getargspec(f)[0]
> def decorator(*args, **keywords):
> bound_instance = args[0]
> for name, value in zip(argnames[1:], args[1:]):
> setattr(bound_instance, name, value)
> return f(*args, **keywords)
> return decorator
>
> #--------- example use:
>
> class foo(object):
> @attribute_decorator
> def __init__(self, thing):
> print "init: self.thing is", repr(self.thing)
>
> f = foo('hello world')
Thanks! Rob Williscroft had a similar suggestion:
http://mail.python.org/pipermail/python-list/2005-July/289734.html
Does anyone know if there is a way to hide the _ or self_ from the user of the
class, i.e. given:
class foo(object):
@attribute_decorator
def __init__(self, x, _y, z):
pass
can we make it such that the user can still write
foo(x=1,y=2,z=3)
without the underscore?
Cheers,
Ralf
__________________________________
Discover Yahoo!
Use Yahoo! to plan a weekend, have fun online and more. Check it out!
http://discover.yahoo.com/
More information about the Python-list
mailing list