In Python, functions have access to variables in the enclosing scope.
As a test of the extent / consistency of this, I did an experiment with creating a simple namespace but did not get the expected behavior. I do not understand why this simple case should be treated differently, is there a good explanation?
Here is a simple example:
import types
bunch = types.SimpleNamespace(
x = 5,
y = 12,
printx = lambda: print(x)
)
Executing bunch.printx() after running the above code will result in a NameError as x is not defined. But we have defined a function "printx" that is enclosed by the bunch namespace, yet the function does not have access to the variables in the enclosing namespace.
In comparison importing the code bunch.py as an external file will place the objects in the bunch namespace with the access to the variables in the enclosing namespace as expected:
bunch.py:
x = 5,
y = 12,
printx = lambda: print(x)
Running the following code will result in printing a 5 as expected:
import bunch
bunch.printx()
I did find this question, which may be related: Python: Access from within a lambda a name that's in the scope but not in the namespace The example I provide here is clearer specific to accessing variables within the enclosing scope.