0

Can anyone tell me why the following code error?
My guess is, the inner function is somehow detecting a 'new' variable declaration, (i have 'x' on a left side on inner() ).
While it fails because this 'x' appears first on the right side. Is this correct?
Am I wrong expecting it to behave normally (i.e Increment the value of x).

In any other context, x can be accessed from the inner function. The only problem happens if I ever put that x on a left side.

def outer(x):
    def inner():
        x = x + 1
        return x
    return inner()

outer(1)

UnboundLocalError: local variable 'x' referenced before assignment

Javier
  • 672
  • 5
  • 13
  • 1
    You are assigning to `x`, which makes it a local. You'll have to explicitly mark it as not a local using the (Python 3 only) statement `nonlocal x`. In Python 2, you cannot do what you want to do like that, you'd have to [use a work-around](https://stackoverflow.com/questions/14678434/passing-argument-from-parent-function-to-nested-function-python/14678445#14678445). – Martijn Pieters Jul 02 '15 at 20:34
  • The question was more about 'why' is happening, which you answer on the duplicate. I wanted to mention that assign to 'x', doesn't necessarily makes it local. In fact you can assign outer x as much as you want, and modify it's value, and it works, still as outer function x. I believe this is an interpreter decision, based on the scope's rules mentioned on the other question. – Javier Jul 02 '15 at 20:46
  • Yes, that is what I am saying. You are assigning (binding) to `x` in the inner function, so the compiler decides it is a local in that function unless explicitly told otherwise. – Martijn Pieters Jul 02 '15 at 20:56

0 Answers0