here is my code:
def f(x):
def g(n):
if n < 10:
x = x + 1
g(n + 1)
g(0)
When I evaluate f(0), there would be an error “x referenced before assignment”.
However, when I use “print x” instead of “x = x + 1” , it will work.
It seems that in the scope of g, I can only use x as an “use occurrence” but not a “binding occurrence”. I guess the problem is that f passes to g only the VALUE of x.
Am I understanding it correctly or not? If not, can someone explain why the left side of “x = x + 1” is not defined before reference?
Thanks
You are understanding it correctly. You cannot use
xto assign to in a nested scope in Python 2.In Python 3, you can still use it as a binding occurrence by marking the variable as
nonlocal; this is a keyword introduced for just this usecase:In python 2, you have a few work-arounds; using a mutable to avoid needing to bind it, or (ab)using a function property:
or