Local variables initialization

Alex Martelli aleaxit at yahoo.com
Sun Feb 26 20:20:02 EST 2006


Michal Kwiatkowski <ruby at no.spam> wrote:
   ...
> The problem wouldn't be such a problem if Python had implicit self...
> but on the other side, it's another ambiguity.

In your example, you could avoid assigning var_one, but the purpose of
assigning var_two and empty_list obviously would not go away with
implicit self (and attendant ambiguities).


> Well, maybe you can help me in refactoring this code, so that it won't
> be such a pain to easily modify groups of methods? I'm thinking about this:
> 
> def init_arguments(fun):
>     def new_f(self):
>         var_one = self.attr_one
>         var_two = self.attr_two.another_attr
>         empty_list = []
> 
>         fun(self, var_one, var_two, empty_list)

You probably want a 'return fun(...)' here, for generality.

>     return new_f
> 
> @init_arguments
> def method(self, var_one, var_two, empty_list):
>     # significant code goes here
>     # ...
> 
> But the bad thing about this approach is that actual method doesn't
> really look like its definition, because of different number of arguments.

Yep, but to avoid black magic those names DO have to be identified as
locals to the compiler at the time of the 'def method(...', which
happens before the decorator gets to play.  If you're keen on using
those barenames as locals in method, there's no clean way out.

Personally, I would give up on the bareness of the names and bunch them
up into a specially named bunch, say _ (single underscore) assuming you
don't need that for other purposes such as i18n.  The method's signature
would be a formulaic 'def method(_, self [other args if any])' -- or you
could swap _ and self, if you wish; and the decorator could supply as _
a magic object (nothing black about it;-) with the suitable behavior,
not just for getting attributes, but also for setting them. If you're
sure you don't need to set them, then a simple Bunch instance with the
usual 'class Bunch: pass', or any other such approach, will suffice.

But of course, then the method's body would have to use _.one rather
than var_one, _.two rather than var_two, and _.empty_list rather than
empty_list (what a strange name -- does it STAY empty throughout the
method's execution?!).  To me this looks like a small price to pay, and
the 'def method(_, self, ...)' signature a clear, strong indication that
something weird, but not TOO weird, is going on. YMMV...


Alex



More information about the Python-list mailing list