user51462
user51462

Reputation: 2022

How does `from <modname> import <attr>` maintain access to non-imported attributes in `modname`?

According to the docs, import <modname> combines two operations:

  1. Search for module named modname
  2. If found, create and initialise a module object and bind it to name modname in the importing scope.

But I can't find a similar explanation for from <modname> import <attr>.

Question

Say attr is a function that refers to some other attributes of modname that were not imported. Why is it that when we only import attr, it is still has access to these other attributes even though they were not imported? Is it just through closures or is a module object created as in import modname?

Example

square.py:

num = 3

def squarenum():
    return num**2

test.py:

from square import squarenum

squarenum()   # prints 9 even though `num` wasn't imported

In the above example, squarenum can still access num even though num was not imported, why is this?

Upvotes: 0

Views: 68

Answers (1)

anthony sottile
anthony sottile

Reputation: 69954

the function object itself maintains a reference to the globals in which it is defined. they are accessible at the __globals__ attribute

$ cat t.py 
x = 1

def f():
    print(x)
>>> from t import f
>>> f.__globals__['x']
1
>>> f()
1
>>> # not that you should ever do this
>>> f.__globals__['x'] = 2
>>> f()
2

Upvotes: 1

Related Questions