2 ms·
This is a consequence of python not having explicit variable definition. Here it'll decide to define a new x instead of seeing the old one. And that's also usu
by faho 5y ago
This is a consequence of python not having explicit variable definition. Here it'll decide to define a new x instead of seeing the old one.
And that's also usually what you want because otherwise a function would start altering variables in the enclosing scope if they happen to exist!
E.g.
foo = 42
def myfunc(bar):
foo = bar + 1
print(foo)
myfunc(6)
print(foo) # would print "7" if the "foo =" above took the nonlocal foo automatically!
So the trade-off is to require "nonlocal" if you ever need a variable from the enclosing scope.