https://docs.python.org/3/reference/import.html
https://docs.python.org/3/library/importlib.html
PEP 328 - Imports: Multi-Line and Absolute/Relative
PEP 810 - Explicit lazy imports.
Introducing the new lazy soft keyword.
lazy import json
lazy from json import dumps
Python code in one module gains access to the code in another module by the process of importing it.
The import statement combines two operations:
(a) searching for the named module [finders],
(b) binding the results of that search to a name in the local scope
[loaders; module execution].
When a module is first imported, Python searches for the module and if found, it creates a module object, initializing it. If the named module cannot be found, a ImportError (Py2) or ModuleNotFoundError (Py3.6+) is raised.
The Python interpreter searches for modules in the following sequences:
(a) the current directory,
(b) directories in the shell variable PYTHONPATH,
(c) default locations (installation-dependent).
The module search path is stored in the system module sys as the sys.path variable.
import sys print(sys.modules.keys()) # names of imported modules print(sys.path) # the module search path
# Using 'import' statements. import module1 # recommended import module2, module3 print(module1.name1) other_name = module1 # modules are objects print(other_name.name1) module1.name1 = new_value # be careful! module1.name2() # a function call print(module1.__doc__) # docstring help(module1) # NAME, FILE, FUNCTIONS, DATA dir(module1) # namespace module1.__dict__.keys() # namespace
# Using 'from ... import' statements. # We can import specific names from a module into the current namespace. from module1 import name1, name2 from module1 import (name1, name2) # for long lists of names # Equivalent statements: # import module1 # name1 = module1.name1 # name2 = module1.name2 # del module1 from module2 import * # importing all names, possible problems print(name1, name2())
import module1 as module2 # Equivalent statements: # import module1 # module2 = module1 # del module1 import numpy as np import Tkinter as tk # Py2 import tkinter as tk # Py3 import pygame as pg
from module3 import name1 as name2
# The reload() function imports a previously imported module again. #reload(module1) # Py2 from importlib import reload # Py3.4+ reload(module1)