3 ms·
I always run into trouble in Python with closures and assignment. E.g., def f(): x = 0 def g(): x += 1 g() f()
by amelius 11y ago
I always run into trouble in Python with closures and assignment. E.g.,
def f():
x = 0
def g():
x += 1
g()
f()
- Veedrac 11y agoHere's a quick interpretation of Python's method: Any assignment operator (compound or not) follows the same namespace rules. Scope lookups are consistent within a scope, regardless of order. Any "namespaced" lookup (`x[y]` and `foo.bar`) will act inside that namespace. Non-namespaced identifiers will always assign into the nearest enclosing scope (a scope is always a named function) by default, since clobbering outer scopes - particularly globals - is dangerous. You can opt in to clobbering with `global` and `nonlocal`. If you don't ever assign to a name in the current scope, lookups will be lexical (since a local lookup cannot succeed). --- Hopefully most of these value judgements should be relatively obvious.