Re: local variable 'a' referenced b

Discussion in 'Python' started by Dave Angel, Oct 3, 2012.

  1. Dave Angel

    Dave Angel Guest

    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
    Dave Angel, Oct 3, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Moscatt
    Replies:
    2
    Views:
    9,792
    Peter Moscatt
    Mar 19, 2005
  2. Replies:
    2
    Views:
    5,276
    Diez B. Roggisch
    Feb 26, 2006
  3. Pete Bartonly
    Replies:
    10
    Views:
    791
    Dennis Lee Bieber
    Oct 25, 2007
  4. Wang, Harry
    Replies:
    2
    Views:
    302
  5. Gabriel Rossetti
    Replies:
    3
    Views:
    947
    Hrvoje Niksic
    Dec 9, 2009
Loading...

Share This Page