Need help with Python scoping rules

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Aug 27 05:31:41 EDT 2009


On Thu, 27 Aug 2009 09:09:21 +0200, Hendrik van Rooyen wrote:

> On Wednesday 26 August 2009 17:45:54 kj wrote:
>> In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano
> <steve at REMOVE-THIS-cybersource.com.au> writes:
> 
>> >Why are you defining a method without a self parameter?
>>
>> Because, as I've explained elsewhere, it is not a method: it's a
>> "helper" function, meant to be called only once, within the class
>> statement itself.
> 
> If the sole purpose of the function is to be used to define what will
> become a constant, why do you not just calculate the constant on your
> calculator, or at the interactive prompt, and assign it to the
> attribute, and be done with it?
> 
> Why waste run time recalculating every time the programme is called?

What you are calculating might actually be quite complicated to enter as 
a literal. You might have something like:

class C(object):
    TABLE = []
    for i in xrange(100):
        row = []
        for j in xrange(100):
            row.append((i**3 + 2*i**2 - i*j + 7*j**2 + 9*i*j**2 - j)/3)
        TABLE.append(row)

It's a little hard to type out C.TABLE as a literal.

And even if you could, which would you rather see if you were debugging 
this class? The above, or:

class C(object):
    TABLE = [
        [0.0, 2.0, 8.6666666666666661, 20.0, 36.0, ... ], 
        [1.0, 5.666666666666667, 21.0, 47.0, 83.666666666666671, ...], 
        [5.333333333333333, 12.666666666666666, 36.666666666666664, ...],
        ...
        [... , 3143161.0, 3201497.6666666665, 3260433.0]
        ]


For obvious reasons I haven't typed the whole thing out! And imagine 
trying to check it for typos!

Clearly this is a made-up example, but the principle is sound. If Python 
can calculate values for you, why not let it do so? It is easier for you, 
easier to check that you've calculated them correctly, easier to debug 
and read, it makes the algorithm clearer (fewer "magic constants"). Yes, 
there is a run-time cost, but you only pay it once, when you import the 
module, and it's likely to be not that much more expensive than parsing 
the literals anyway.

Of course, for something as big and complicated as the above table, I'd 
almost certainly put the code to calculate it in a function outside of 
the class, but that's a matter of style, and it will work to put it 
inside the class.



-- 
Steven



More information about the Python-list mailing list