UnboundLocalError - (code is short & simple)

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Sep 28 04:24:51 EDT 2009


Chris Rebert a écrit :
> 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
(snip)
> To fix the problem, rename the variable so its name differs from that
> of the coin_toss() function. 
(snip)

<OP>
As an additional note: in Python, everything is an object - including 
modules, classes, and, yes, functions -, so there's no distinct 
namespace for functions or classes. If you try to execute the "coin_toss 
= coin_toss()" statement at the top level (or declare name 'coin_toss' 
global prior using it in the toss_winner function), you wouldn't get an 
UnboundLocalError, but after the very first execution of the statement 
you would probably get a TypeError on subsquent attempts to call coin_toss:

 >>> def coin_toss():
...      print "coin_toss called"
...      return 42
...
 >>> coin_toss
<function coin_toss at 0x952517c>
 >>> coin_toss = coin_toss()
coin_toss called
 >>> coin_toss
42
 >>> coin_toss()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
 >>>

</OP>

HTH









More information about the Python-list mailing list