0

I have something like this:

def a():
  #do something
  foo = 0
  def b():
    foo += 2
    # do something
  b()
  #do something

a()

but it says

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a()
  File "<pyshell#5>", line 7, in a
    b()
  File "<pyshell#5>", line 5, in b
    foo += 2
UnboundLocalError: local variable 'foo' referenced before assignment

How can I access foo without making it global?

1 Answer 1

3

The assignment to foo in b makes it a local variable, unrelated to the variable of the same name in a. Use the nonlocal statement to change that.

def a():
    #do something
    foo = 0
    def b():
        nonlocal foo
        foo += 2
        # do something
    b()
  #do something

Now foo in b is the same variable as foo in a. nonlocal is like global, but uses the closest enclosing scope that contains the name foo rather than jumping straight to the global scope.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.