Local variables initialization

Michal Kwiatkowski ruby at no.spam
Sun Feb 26 20:08:24 EST 2006


Alex Martelli wrote:
> Michal Kwiatkowski <ruby at no.spam> wrote:
>    ...
>> def method(self):
>>     var_one = self.attr_one
>>     var_two = self.attr_two.another_attr
>>     empty_list = []
>>     # significant code goes here
>    ...

> Personally, I would keep pushing back against this approach even after
> I'd gone to the trouble of implementing it more solidly -- in no way is
> clarity served by having magic local variables appear out of the blue
> (or, rather, the black of black magic).  However, whether something CAN
> be done, and whether it SHOULD be done, are separate issues.

I agree with your approach to local variables appearing out of nowhere,
but still, it's a real pain to copy-and-paste few lines of this standard
initialization to each new method I add. And then imagine another local
variable will be needed and I have to change every single method...
That's even more bug prone than magic-variables approach, if you ask me.
The problem wouldn't be such a problem if Python had implicit self...
but on the other side, it's another ambiguity.

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)

    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.

mk
-- 
 . o .       >>  http://joker.linuxstuff.pl  <<
 . . o   It's easier to get forgiveness for being wrong
 o o o   than forgiveness for being right.



More information about the Python-list mailing list