Confused by Python and nested scoping (2.4.3)

Kelvie Wong kelvie at ieee.org
Wed Apr 19 19:00:48 EDT 2006


There are only two scopes in Python -- global scope and function scope.

On 4/19/06, Sean Givan <kinsman at nbnet.nb.ca> wrote:
> Hi.  I'm new to Python, and downloaded a Windows copy a little while
> ago.  I was doing some experiments with nested functions, and ran into
> something strange.
>
> This code:
>
> def outer():
>         val = 10
>         def inner():
>                 print val
>         inner()
>
> outer()
>
> ..prints out the value '10', which is what I was expecting.
>
> But this code..
>
> def outer():
>         val = 10
>         def inner():
>                 print val
>                 val = 20
>         inner()
>         print val
>
> outer()
>
> ..I expected to print '10', then '20', but instead got an error:
>
>    print val
> UnboundLocalError: local variable 'val' referenced before assignment.
>
> I'm thinking this is some bug where the interpreter is getting ahead of
> itself, spotting the 'val = 20' line and warning me about something that
> doesn't need warning.  Or am I doing something wrong?
>
> Thanks,
> -Sean Givan
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--
Kelvie



More information about the Python-list mailing list