[Tutor] Global/Local confusions

John Abbe johnca@ourpla.net
Wed Mar 12 05:48:05 2003


At 1:57 PM +0100 2003-03-11, Abel Daniel wrote:
>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.

Well, i feel better knowing that the things that led me to annoyance 
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

Thanks...i'm beginning to get how important this identity/contents 
distinction is.

Life,
John
-- 
  All you  /\/\ John Abbe           "If you don't like the news,
      need \  / CatHerder            go out and make some of your own."
      is... \/  http://ourpla.net/john/                --Wes Nisker