Load a module
Reuse functionality implemented in another module or package.
Python · Const
The import statement finds and initializes modules as needed, then binds modules or selected names in the current namespace. It supports aliases, qualified module paths, relative imports, and from ... import ... forms.
An import statement locates a module, loading and initializing it when needed, then creates bindings in the current scope. The basic form binds a top-level module name, while from imports bind selected attributes or submodules directly; as supplies an explicit alias.
["lazy"] "import" module ["as" identifier] ("," module ["as" identifier])* | ["lazy"] "from" relative_module "import" identifier ["as" identifier] ("," identifier ["as" identifier])*| Name | Type | Description |
|---|---|---|
module / relative_module / identifier | module name or identifier | One or more module paths, optionally followed by aliases or imported identifiers. |
It binds imported modules or values in the current namespace; the statement itself has no user-visible return value.
as to choose the local name assigned to an imported module.import math
from pathlib import Path as FilePath
print(math.sqrt(16))
print(FilePath('.').resolve())This imports the math module under its original name and binds Path under the alias FilePath.
Reuse functionality implemented in another module or package.
Expose a shorter or clearer local name for a module or imported value.
Bring selected functions, classes, or constants into the current namespace.
Load a package-relative module within a package hierarchy.
The statement first finds the requested module, loading and initializing it if necessary. It then binds the resulting module or imported values in the current namespace.
Follow-up: How does from package import name resolve name? It checks the package for an attribute, then may try a submodule and checks again before raising ImportError.
import and from ... import ... differ?import package.module normally binds the top-level package name, so the nested module is accessed through its qualified name. from package.module import name instead stores the selected value directly in the current namespace.
Follow-up: What changes when as alias is used? The alias becomes the binding name for the imported module or value.
as clause do?An alias gives the imported module or value an explicit local binding. Without an alias, a top-level module normally binds its own name; with as, the name after as is bound directly.
Follow-up: Where is wildcard import permitted? Only at module level, not inside class or function definitions.
importlib.import_module()__import__()modulerelative_moduleImportError