UnboundLocalError - (code is short & simple)

New User for_python at yahoo.com
Mon Sep 28 16:52:41 EDT 2009


Thanks for the light you shed on the "namespace" issue, and for the additional info and code example.  I'll be studying more about the info you shared.  Also, I tried out your code example, to get firsthand experience with it. 

Cheers,
Martin

--- On Mon, 9/28/09, Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> wrote:

From: Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid>
Subject: Re: UnboundLocalError - (code is short & simple)
To: python-list at python.org
Date: Monday, September 28, 2009, 8:24 AM

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






-- http://mail.python.org/mailman/listinfo/python-list



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090928/6f4948d5/attachment-0001.html>


More information about the Python-list mailing list