3 ms·
>If you call a function that happens to refer to a variable that only exists in the calling code, it will work This is not true. This code gives a NameError in
by duckerude 8y ago
>If you call a function that happens to refer to a variable that only exists in the calling code, it will work
This is not true. This code gives a NameError instead of printing "1":
def f1():
print(var)
def f2():
var = 1
f1()
f2()
If it can't find a name in the local scope, it will look in enclosing functions, then the module scope, then the builtins. But it will never look inside the caller's scope unless the function is defined in the caller's scope.
Python's implicit scoping can be confusing, but it's not quite that bad.