[Tutor] Global/Local confusions

Abel Daniel abli@freemail.hu
Tue Mar 11 07:59:01 2003


On Tue, Mar 11, 2003 at 01:15:02PM +0630 John Abbe (johnca@ourpla.net) wrote:
> Sometimes the parser decides i mean a global variable even when i do 
> not explicitly label it. E.g.:
> 
> x = [3]
> def f():
>    if x[0] == 3:
>       print "spam"
> 
> f()
> 
> This assumption-of-global-ness seems to be limited to cases when 
> there is no plain assignment to the variable anywhere in the local 
> context. Why not extend the assumption-of-global-ness to cases when 
> assignment only occurs after any reference?
IIRC the rationale is that cases like this are often programmer errors.
Typos, leaving out a line and so on.

Of course continuing this line of thought, you might demand an explicit
"global" everywhere a global variable is used. Which would also follow
the idea that
"Explicit is better than implicit." (from the zen of python)
However, in the same contains the line
"[...]practicality beats purity."
(http://www.python.org/doc/Humor.html#zen)
and in this case, the current state is a compromise.
> 
[.. snipped some ..]
> To confuse things further, while Python complains about plain assignment:
> 
> x = [3]
> def f():
>    if x[0] == 3:
>       print "spam"
>       x = [3, 5]
> 
> f()
> x
> 
> ...assignment by object method is okay:
> 
> x = [3]
> def f():
>    if x[0] == 3:
>       print "spam"
>       x.append(5)
> 
> f()
> x
> 
> Why? And is there anything else i should know about recognizing when 
> a variable will be auto-recognized as global?
In this case you don't modify x. Try printing id(x) before and after.
In the second case x's content changes, but the identity of x doesn't.
For more explanation see
http://effbot.org/guides/python-objects.htm
and
http://starship.python.net/crew/mwh/hacks/objectthink.html

--
Abel Daniel