Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing `from abc import xyz` where does the module `abc` go?

Question about Python internals. If I execute import abc then Python reads the module into a new namespace and binds the variable abc in the global namespace to point to the new namespace.

If I execute from abc import xyz then it reads the entire module abc into some new namespace and then binds the variable xyz in the global namespace to the same object which is bound to xyz in this newly created namespace where the module was read into. At least that's my understanding.

What happens to the namespace where abc was read into after that? I'm assuming it lives on somewhere, because xyz might access other objects in that namespace. Can this "ghost" abc namespace be accessed somehow?

Also, I'm assuming that if I do

from abc import xyz
from abc import fgh

then there is only one "ghost" abc namespace, so that if xyz and fgh modify the same global variable in abc, there will only be one copy of it. Is that correct?

like image 899
mrip Avatar asked Apr 07 '16 15:04

mrip


People also ask

What does from import mean in Python?

Importing refers to allowing a Python file or a Python module to access the script from another Python file or module. You can only use functions and properties your program can access. For instance, if you want to use mathematical functionalities, you must import the math package first.

What is __ all __ in Python?

Python __all__ It's a list of public objects of that module, as interpreted by import * . It overrides the default of hiding everything that begins with an underscore.


1 Answers

The module object is stored in sys.modules. So if you do from abc import xyz, then sys.modules['abc'] will give you the abc module object.

like image 133
BrenBarn Avatar answered Sep 21 '22 13:09

BrenBarn