py3k feature proposal: field auto-assignment in constructors
Terry Reedy
tjreedy at udel.edu
Sun Jan 27 19:13:27 EST 2008
"André" <andre.roberge at gmail.com> wrote in message
news:7dcc86da-6ed7-48ec-9a9e-ada5574ae06e at v17g2000hsa.googlegroups.com...
If one goes back to the original idea instead, the decision of using
automatic assignment should depend on the signature of the __init__
function. Here's an implementation (using "_" instead of "." as it
would lead to a syntax error):
from functools import *
from inspect import *
def autoassign(_init_):
@wraps(_init_)
def _autoassign(self, *args, **kwargs):
argnames, _, _, _ = getargspec(_init_)
for name, value in zip(argnames[1:], args):
if name.startswith("_"):
setattr(self, name[1:], value)
_init_(self, *args, **kwargs)
return _autoassign
class Test(object):
@autoassign
def __init__(self, _foo, _bar, baz):
print 'baz =', baz
t = Test(1, 2, 3)
print t.foo
print t.bar
print t.baz
#== the output is
baz = 3
1
2
Traceback (most recent call last):
File "/Users/andre/CrunchySVN/branches/andre/src/tools_2k.py", line
24, in exec_code
exec code in local_dict
File "User's code", line 23, in <module>
AttributeError: 'Test' object has no attribute 'baz'
=================================
I think this version, with this name convention, is nice enough to possibly
go in the stdlib if there were an appropriate place for it. Not sure where
though. If there were a classtools module....
tjr
More information about the Python-list
mailing list