confusing UnboundLocalError behaive

Chris Rebert clp2 at rebertia.com
Mon Feb 23 03:26:17 EST 2009


On Mon, Feb 23, 2009 at 12:06 AM, neoedmund <neoedmund at gmail.com> wrote:
> see the 3 small piece of code, i cannot understand why it result as
> this.
>
> 1.
> def test():
>        abc="111"
>        def m1():
>                print(abc)
>        m1()
> test()
>
> Output: 111
>
> 2.
> def test():
>        abc="111"
>        def m1():

You need a 'nonlocal' declaration here (requires Python 3.0 I think).
See PEP 3104 for more info -- http://www.python.org/dev/peps/pep-3104/

>                print(abc)
>                abc+="222"
>        m1()
> test()
>
> Output:
>   print(abc)
> UnboundLocalError: local variable 'abc' referenced before assignment
>
> 3.
> def test2():
>        abc=[111]
>        def m1():
>                print(abc)
>                abc.append(222)
>        m1()
>        print(abc)
> test2()
>
> Output:
> [111]
> [111,222]
>
> it seems "you cannot change the outter scope values but can use it
> readonly."

Yeah, that's basically how nested scopes (sans 'nonlocal') work in
Python, since assignment typically constitutes an implicit scope
declaration.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list