Reputation: 2022
According to the docs, import <modname>
combines two operations:
modname
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
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