Can local function access local variables in main program?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Nov 3 03:34:47 EDT 2007


On Sat, 03 Nov 2007 07:18:17 +0000, Sullivan WxPyQtKinter wrote:

> def f():
>     print x
>     x=0
> 
> x=12345
> f()
> 
> result is:
> Traceback (most recent call last):
>   File "...\test.py", line 5, in ?
>     f()
>   File "...\test.py", line 2, in f
>     print x
> UnboundLocalError: local variable 'x' referenced before assignment


When Python compiles your function f(), it sees that you have assigned to 
x, and that there is no line "global x", so it knows that x is a local 
variable.

But when you call f(), you try to print x before the local x has a value 
assigned to it. Hence the (accurate but hardly user-friendly) error 
message.

You can also do this:

>>> help(UnboundLocalError)

Help on class UnboundLocalError in module exceptions:

class UnboundLocalError(NameError)
 |  Local name referenced but not bound to a value.



As far as I know, there is no way to read the value of global x if and 
only if local x doesn't exist. 



-- 
Steven



More information about the Python-list mailing list