UnboundLocalError - (code is short & simple)

Chris Rebert clp2 at rebertia.com
Mon Sep 28 06:17:57 CEST 2009


On Sun, Sep 27, 2009 at 8:53 PM, pylearner <for_python at yahoo.com> wrote:
<snip>
> -------------------------------------------------------------------
>
> Traceback (most recent call last):
>  File "<pyshell#2>", line 1, in <module>
>    toss_winner()
>  File "C:/Python26/toss_winner.py", line 7, in toss_winner
>    coin_toss = coin_toss()
> UnboundLocalError: local variable 'coin_toss' referenced before
> assignment
>
> ---------------------------------------------------------------
>
> # toss_winner.py
>
> from coin_toss import coin_toss
>
> def toss_winner():
>
>    coin_toss = coin_toss()

When Python sees this assignment to coin_toss as it compiles the
toss_winner() function, it marks coin_toss as a local variable and
will not consult global scope when looking it up at runtime (this is
an implementation optimization that leaks into the language level).
Hence, when the function is executed, Python does a fast lookup of
coin_toss in the local scope, finds it has not been assigned to, and
raises the error you're seeing, not falling back to and examining the
global variable scope.

To fix the problem, rename the variable so its name differs from that
of the coin_toss() function. That way, Python won't optimize the
lookup and will consult the global scope when it goes to resolve
coin_toss() in toss_winner().

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list