Behaviour of print in functions
Craig McLean
craigmclean at shaw.ca
Wed Jul 10 16:11:33 EDT 2002
I'm learning Python and I have run into something I can't explain. I have
the following code
X = 99
def foo():
print X
X = 100
print X
foo()
When I call foo it complains that local variable X is referenced before been
assigned. However X is a global and I was under the impression that it
should realize that and resolve it automatically.
I know that if you add a "global X" as the first line of function foo then
this all works properly.
I also know that
X=99
def qux():
print X
qux()
prints 99 as I would expect.
I'm assuming what is happening is that name resolutions use the LGB rule,
but assignments always create a new entry in the local namespace, without
checking to see if it is covering up a global object of the same name. I'm
also assuming that this happens before any of the code in the function is
executed.
Am I correct? Or is something else happening here.
More information about the Python-list
mailing list