[Tutor] scoping oddity
Brian van den Broek
bvande at po-box.mcgill.ca
Sat May 7 18:22:17 CEST 2005
Bob Gailer said unto the world upon 2005-05-07 11:46:
> At 07:43 AM 5/7/2005, Brian van den Broek wrote:
>
>> Michael.Coll-Barth at VerizonWireless.com said unto the world upon
>> 2005-05-07 09:56:
>> > Good morning,
>> >
>> > I came across a rather odd issue with scoping. Can someone explain why
>> > testa and testc works, but not testb. I am running under python
>> 2.4.1 on
>> > Windows NT.
>> >
>> > thanks,
>> > Michael
>>
>> <SNIP>
>>
>> > def testb(astr):
>> > x = x - 1
>> > print astr, x
>>
>> `x =', with a function def, gets interpreted as "create a new name x
>> in the function-local scope and bind it to whatever is on the right of
>> the `='. But, on the right is an expression involving x itself. You
>> might expect Python to look to the global scope to find x, but by
>> writing `x =', you've already settled that x will be a local scope
>> name, so it looks only in the local scope. Of, course, when it gets to
>> `x -1', x hasn't yet been given a reference and it all barfs.
>
>
> This is what the global statement is for:
>
> def testb(astr):
> global x
> x = x - 1
> etc.
>
> Bob Gailer
global will indeed fix that, yes. But, I've been lead to believe that
one's first thought when tempted to write a global statement should be
to reflect on whether that temptation isn't the symptom of a
sub-optimal design. It certainly can (in my case has) lead to bugs
when two separate bits of code both declare the same name global and
thus each make their changes to it, after I have forgotten that I made
both functions declare the name global.
While nothing is guaranteed to protect me from myself :-) I have found
I make fewer such mistakes when I either design my functions to
explicitly take in the argument and return its modified value or
instead employ a class and store the data as an instance attribute
where the qualifier of self helps me to keep the issues straight.
And, to engage in appeal to authority (almost the last refuge of the
scoundrel): lots of Python programmers more accomplished than I seem
to have the achieved a consensus that global is to be avoided.
Best,
Brian vdB
More information about the Tutor
mailing list