py3k feature proposal: field auto-assignment in constructors

Diez B. Roggisch deets at nospam.web.de
Sun Jan 27 13:32:08 EST 2008


Wildemar Wildenburger schrieb:
> André wrote:
>> Personally, I like the idea you suggest, with the modification that I
>> would use "." instead of "@", as in
>>
>> class Server(object):
>>     def __init__(self, .host, .port, .protocol, .bufsize, .timeout):
>>         pass
>>
> I like :)
> 
> However, you can probably cook up a decorator for this (not certain, I'm 
> not a decorator Guru), which is not that much worse.
> 
> Still, I'd support that syntax (and the general idea.).

Just for the fun of it, I implemented a decorator:

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):
             setattr(self, name, value)
         _init_(self, *args, **kwargs)

     return _autoassign

class Test(object):
     @autoassign
     def __init__(self, foo, bar):
         pass



t = Test(10, 20)

print t.bar


Diez



More information about the Python-list mailing list