Proposal: reducing self.x=x; self.y=y; self.z=z boilerplate code

Thomas Heller theller at python.net
Tue Jul 5 15:06:14 EDT 2005


mcherm at gmail.com writes:

> Ralf W. Grosse-Kunstleve wrote:
>> I often find myself writing::
>>
>>     class grouping:
>>
>>         def __init__(self, x, y, z):
>>             self.x = x
>>             self.y = y
>>             self.z = z
>>             # real code, finally
>>
>> This becomes a serious nuisance in complex applications with long
>> argument lists
>
> Yes... indeed it does. This is so common that there is a standard
> idiom for handling it:
>
>     def __init__(self, x, y, z):
>         self.__dict__.update(locals())
>
> sometimes with modifications to avoid setting self.self.

>> I am actually using a simple trick::
>>
>>     adopt_init_args(self, locals())
>
> If the implementation is only 3-4 lines long (and a simpler
> implementation can be), then is can simply be included inline with
> every script that needs to use it.
>
>>   - The ``adopt_init_args(self, locals())`` incantation is hard to
>>     remember and difficult to explain to new-comers.
>
> A better name would help with this. The need for locals() is
> unavoidable.

Ahem - sys._getframe()

Thomas



More information about the Python-list mailing list