Can local function access local variables in main program?

Stargaming stargaming at gmail.com
Sat Nov 3 03:39:20 EDT 2007


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

> I am confused by the following program:
> 
> def f():
>     print x
> x=12345
> f()
> 
> result is:
>>>>
> 12345

If python can't discover x in your current scope and you do not bind to 
it there, it will automatically access that global name x.

> however:
> 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

Here, you *do* assign to x in this scope so this is essentially the same 
as the following (without any function scope)::

    print x
    x = 12345

This can't work since you haven't used x when you try to print it.

You can make this work using the `global` statement::

    >>> def foo():
    ...     global x
    ...     print x
    ...     x = 0
    ...
    >>> x = 12345
    >>> print x
    12345
    >>> foo()
    12345
    >>> print x
    0

See more in the `lexical reference about the global statement <http://
docs.python.org/ref/global.html>.

HTH,
Stargaming



More information about the Python-list mailing list