How from ... import ... statement to import global variables

I can't figure out how this works under the hood. I have the following files:

test.py

x = 20

def foo():
    print x

      

test2.py

from test import foo

foo()

      

When I import the foo function in test2.py, how does it resolve x. As far as I know, only the function foo is imported from the test import import foo.

0


source to share


2 answers


Functions keep a reference to their global modules. foo

has a link like this:

>>> 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 serves as the global namespace for this module. The operator then import

binds the names in your local module to the same object or to the attributes of that object.



Functions refer to the same namespace to find global tables from where they were defined; they are essentially referring to the same dictionary:

>>> import sys
>>> foo.__globals__ is sys.modules['test'].__dict__
True

      

+4


source


This thing, when a function remembers the entire environment in which it was defined, is called a closure .



0


source







All Articles