Python Glossary Русский

Python 3.8+astterm

ast.FunctionType

root and base nodes

The root for mode='func_type': parses an old-style function type comment like '(int, str) -> bool' into argtypes and returns.

Syntax

ast.parse('(argtypes) -> returns', mode='func_type')  # → ast.FunctionType

The node serves tools like mypy that read '# type: (int) -> str' comments from code written before annotations. ast.parse does not pick these comments up by itself: pass type_comments=True, then the text sits in FunctionDef.type_comment, and you parse it separately in 'func_type' mode. Such a tree can be neither executed nor compiled.

Examples

import ast
ft = ast.parse('(int, str) -> bool', mode='func_type')
print(type(ft).__name__)  # → FunctionType
print([a.id for a in ft.argtypes], ft.returns.id)  # → ['int', 'str'] bool
import ast
src = 'def f(a):\n    # type: (int) -> str\n    return str(a)'
fn = ast.parse(src, type_comments=True).body[0]
print(fn.type_comment)  # → (int) -> str
print(ast.parse(fn.type_comment, mode='func_type').returns.id)  # → str

See also

Open in the full glossarydocs.python.orgReport an inaccuracy