Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: local variable 'a' referenced b

Reply
Thread Tools

Re: local variable 'a' referenced b

 
 
Dave Angel
Guest
Posts: n/a
 
      10-03-2012
On 10/02/2012 10:03 PM, contro opinion wrote:
> code1
>>>> def foo():

> ... a = 1
> ... def bar():
> ... b=2
> ... print a + b
> ... bar()
> ...
> ...
>>>> foo()

> 3
>
> code2
>>>> def foo():

> ... a = 1
> ... def bar():
> ... b=2
> ... a = a + b


Because your function bar() has an assignment to a, it becomes a local,
and masks access to the one in the containing function.

Then because when you start executing that assignment statement, a
hasn't yet gotten a value, you get the error below.

> ... print a
> ... bar()
> ...
>>>> foo()

> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 7, in foo
> File "<stdin>", line 5, in bar
> UnboundLocalError: local variable 'a' referenced b
>
> why code2 can not get output of 3?
>


In Python3, you can avoid the "problem" by declaring a as nonlocal.


def foo():
a = 1
def bar():
nonlocal a
b=2
a = a + b
print (a)
bar()

foo()

if you're stuck with Python2.x, you can use a mutable object for a, and
mutate it, rather than replace it. For example,


def foo():
a = [3]
def bar():
b=2
a.append(b) #this mutates a, but doesn't assign it
print (a)
a[0] += b #likewise, for a number within the list
print (a)
bar()

That should work in either 2.x or 3.2

--

DaveA

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
UnboundLocalError: local variable '_[1]' referenced before assignment Gabriel Rossetti Python 3 12-09-2009 02:48 PM
Error: UnboundLocalError: local variable 'PfFlag' referenced beforeassignment Wang, Harry Python 2 12-01-2007 06:13 PM
local variable referenced before assignment Pete Bartonly Python 10 10-25-2007 05:08 PM
UnboundLocalError: local variable 'colorIndex' referenced silverburgh.meryl@gmail.com Python 2 02-26-2006 09:29 PM
HELP:UnboundLocalError: local variable '_nntp' referenced before assignment Peter Moscatt Python 2 03-19-2005 08:37 AM



Advertisments