Python Glossary Русский

all Python 3astterm

ast.Import

imports

The node for the statement import a, b.c as d: names is a list of alias nodes with name (the full dotted name) and asname.

Syntax

ast.Import(names)

One statement with several modules gives one Import with several alias nodes, not several Import nodes. A dotted name is not split: 'import os.path' is alias(name='os.path'), although only os is bound in the namespace. An import inside a function or try is the same Import deeper in the tree, so find imports with ast.walk rather than by scanning tree.body.

Examples

import ast
imp = ast.parse('import os.path, numpy as np').body[0]
print(type(imp).__name__, [(a.name, a.asname) for a in imp.names])  # → Import [('os.path', None), ('numpy', 'np')]
import ast
src = 'import json\ndef f():\n    import re\n    from x import y'
mods = [a.name for n in ast.walk(ast.parse(src)) if isinstance(n, ast.Import) for a in n.names]
print(sorted(mods))  # → ['json', 're']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy