What happens to module's variables after a "from module import" ?

Peter Otten __peter__ at web.de
Tue Nov 7 10:57:09 EST 2017


ast wrote:

> Hello
> 
> Here is my module tmp.py:
> 
> a=0
> 
> def test():
>     global a
>     print(a)
>     a+=1
> 
> If I import function "test" from module "tmp" with:
> 
>>>> from tmp import test
> 
> it works
> 
>>>> test()
> 0
>>>> test()
> 1
> 
> But where variable "a" is located ? I can't find it anywhere

The function keeps a reference to the global namespace of the tmp module.

>>> from tmp import test
>>> test.__globals__["a"]
0
>>> test()
0
>>> test.__globals__["a"]
1

The module is cached; thus a subsequent import gives the same function and 
of course accesses the same global namespace:

>>> from tmp import test as test2
>>> test is test2
True
>>> test2()
1

When you remove the module from the cache (usually a bad idea, done here for 
demonstration purposes) you will get a new function and a new global 
namespace:

>>> import sys
>>> del sys.modules["tmp"]
>>> from tmp import test as test3
>>> test is test3
False
>>> test()
2
>>> test3()
0





More information about the Python-list mailing list