Direct name imports
Use a class or function without qualifying every reference with its module name.
Python · Const
from is part of Python’s import statement: it selects names from a module and binds them in the current namespace, optionally under aliases. Leading dots enable package-relative imports.
The from form imports a named attribute from a module and binds it in the current namespace. A dotted module path and relative leading dots are supported, and as can provide a different local name.
from relative_module import identifier [as identifier]
from relative_module import (identifier [as identifier], ...)
from relative_module import *| Name | Type | Description |
|---|---|---|
relative_module | module path | Module or relative module containing the names to import. |
identifier | identifier | One or more attributes or submodules to bind locally. |
The statement binds imported values in the current namespace; it does not have a function return value.
from pathlib import Path
config_path = Path("config.json")
print(config_path.name)This imports Path directly from pathlib, so the local name Path refers to that class.
Use a class or function without qualifying every reference with its module name.
Avoid a local naming conflict or clarify a dependency’s role.
Share code between modules within the same package.
The from form first finds and initializes the module named in the from clause. For each requested identifier, Python checks for an attribute, may try a submodule, and raises ImportError if the name is not found.
Follow-up: What name is bound when as is present? The alias is used; otherwise the imported attribute name is bound locally.
from package import name binds the selected name in the current namespace, rather than binding only the package name. An as clause changes the local binding name.
Follow-up: How would you import a sibling module? Use a relative form such as from . import sibling within a package.
The grammar permits one or more identifiers, optionally aliased, and also permits parenthesized multiline imports. It additionally permits wildcard imports, but only at module scope.
Follow-up: What does from . import mod mean? It imports mod from the package containing the importing module.
import statementrelative importsimportlib.import_module()__import__()