The import and from-import statements are somewhat confusion for beginners to Python.
Here we will discuss some common issues related to import and from-import.
Python have 3 different ways to import modules.
1. import statement
2. from statement
3. builtin __import__ function
import X imports the module X, and creates a reference to that module in the current namespace.So you have to use X.name to refer to things defined in module X.
from X import * imports the module X, and creates references in the current namespace to all public objects defined by that module (that is, everything that doesn’t have a name starting with “_”) hence you can simply use a plain name to refer to things defined in module X. Since X itself is not defined, so X.name doesn’t work.
from X import a, b, c imports the module X, and creates references in the current namespace to the given objects i.e a,b,c.
X = __import__('X') is like import X, with the difference that you pass the module name as a string and explicitly assign it to a variable in your current namespace.
While Python imports a module, it first checks the module registry (sys.modules) to know if the module is already imported.In that case, Python uses the existing module object as is.Otherwise, python do the following:
1. Create a new, empty module object (this is essentially a dictionary)
2. Insert that module object in the sys.modules dictionary
3. Load the module code object (if necessary, compile the module first)
4. Execute the module code object in the new module’s namespace. All variables assigned by the code will be available via the module object.
- Kiran's blog
- 758 reads













Post new comment