How Does From ... Import ... Statement Import Global Variables
I can't figure out how does it works under the hood. I have following files: test.py x = 20 def foo(): print x test2.py from test import foo foo() When I import the foo fun
Solution 1:
Functions retain a reference to their module globals. foo
has such a reference:
>>> from test import foo
>>> foo.__globals__
{'x': 20, 'foo': <function foo at 0x102f3d410, ...}
What happens is that Python creates a module object when you import something; this object is stored in sys.modules
and it serves as the global namespace for that module. The import
statement then binds names in your 'local' module to either that same object or to attributes of that object.
Functions reference the same namespace for looking up globals from where they were defined; they essentially reference the same dictionary object:
>>> import sys
>>> foo.__globals__ is sys.modules['test'].__dict__
True
Solution 2:
This thing, when function remembers all environment in wich it was defined is called closure.
Post a Comment for "How Does From ... Import ... Statement Import Global Variables"