4 ms·
Try this: def f(): def g(): nonlocal x # change this line x = 3 print("x == {!r}".format(x)) x = 2 g()
by ptx 9y ago
Try this:
def f():
def g():
nonlocal x # change this line
x = 3
print("x == {!r}".format(x))
x = 2
g()
print("x == {!r}".format(x))
x = 1
f()
print("x == {!r}".format(x))
It will print (because g reassigns the x in f):
x == 3
x == 3
x == 1
and if you change "nonlocal" to "global", g will reassign the global x, and you get:
x == 3
x == 2
x == 3
and if you remove the line entirely, the assignments will be interpreted as declaring new variables in each scope, and you get :
x == 3
x == 2
x == 1
- jwdunne 9y agoI just looked up the nonlocal keyword, my python isn't strong. I'll hold my hands up - python wasn't a good example here. I was under the impression you could use and mutate outer scope variable.