global variable not seen (bug?)

Christopher A. Craig com-nospam at ccraig.org
Wed Jan 8 16:38:16 EST 2003


Michal Vitecek <fuf at mageo.cz> writes:

>  i must say that this behaviour is pretty strange (non-intuitive at
>  least). why is it that the function looks for that variable in the
>  scope of its module? wouldn't that be more intuitive if it looked
>  for the variable in the current global scope?

I can't speak on whether or not it is intuitive.  It made perfect
sense to me, but I sat down and read not only the tutorial but also
the language reference before I started programming in Python and had
a decent grasp of what Python calls the 'global namespace'.

You're missing something very important though: It does look for the
variable in the current global scope.  Python namespaces are _very_
nice when you get used to them and have helped me to start overcoming
my childhood-trauma-induced fear of global variables.  Python
namespaces are completely static.  Where you call a function has
absolutely no effect on where its global namespace resides.

If you write a module x like this:
-----
state_var = 0

def foo(a, b):
   global state_var
   state_var=a+b
   return a+b
-----

then do 'from x import foo' in a program the global namespace for
foo() is the namespace of the module, not the namespace of the
caller.  This is very nice.  It means that when you write a library you
can use state variables without fear that some program author will
trample over their values.  Furthermore you can be certain that even
if your module is imported multiple times, you only have one state
variable.

There are very few good uses for global variables (even the much nicer
Python kind), but allowing the global namespaces to be modular goes a
long way to solving the problems with them.

-- 
Christopher A. Craig <com-nospam at ccraig.org>
"Never let schooling get in the way of your education"  Mark Twain





More information about the Python-list mailing list