7

It's ok to get and print the outer function variable a

def outer():
    a = 1
    def inner():
        print a

It's also ok to get the outer function array a and append something

def outer():
    a = []
    def inner():
        a.append(1)
        print a

However, it caused some trouble when I tried to increase the integer:

def outer():
    a = 1
    def inner():
        a += 1 #or a = a + 1
        print a

>> UnboundLocalError: local variable 'a' referenced before assignment

Why does this happen and how can I achieve my goal (increase the integer)?

3
  • Of course, you could also pass a to inner from outer. Commented Dec 21, 2012 at 7:04
  • 2
    @sberry: That will not allow what he's trying to do, since it will create a new local variable inside inner, changes to which will not be reflected in outer. Commented Dec 21, 2012 at 7:04
  • Right, unless it is returned, or the OP only has use of a within inner anyway. Commented Dec 21, 2012 at 7:06

3 Answers 3

6

In Python 3 you can do this with the nonlocal keyword. Do nonlocal a at the beginning of inner to mark a as nonlocal.

In Python 2 it is not possible.

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

1 Comment

The only direct and correct answer here... Thx!
3

Workaround for Python 2:

def outer():
    a = [1]
    def inner():
        a[0] += 1
        print a[0]

Comments

3

A generally cleaner way to do this would be:

def outer():
    a = 1
    def inner(b):
        b += 1
        return b
    a = inner(a)

Python allows a lot, but non-local variables can be generally considered as "dirty" (without going into details here).

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.