Typed-AST
typed-ast is a Python 3 package that provided parsers for Python 2.7 and Python 3 (up to 3.7) Abstract Syntax Trees (ASTs). Unlike the standard `ast` module before Python 3.8, it included support for PEP 484 type comments and was independent of the Python version it was run on. The project is currently at version 1.5.5 and is no longer actively maintained, with recommendations to use the built-in `ast` module for Python 3.8+.
Warnings
- breaking The `typed-ast` project is no longer actively maintained. Its primary functionality (parsing type comments) was merged into the standard library `ast` module starting with Python 3.8. It does not support parsing syntax introduced in Python 3.8 or newer.
- gotcha Installation can fail with 'Failed building wheel for typed-ast' errors, especially on Windows, if C/C++ build tools (like Microsoft Visual C++ Build Tools) are not installed, as `typed-ast` contains C extensions.
- gotcha When modifying or creating ASTs using `typed-ast`, it is not always a direct drop-in replacement for the standard `ast` module. Some `typed-ast` classes have additional fields (e.g., for type comments) that must be populated, which can lead to unexpected behavior or errors if not handled.
- gotcha The `typed-ast` library does not support PyPy and there are no plans for future support due to its reliance on specific CPython C APIs.
Install
-
pip install typed-ast
Imports
- typed_ast.ast3.parse
from typed_ast import ast3 ast3.parse(code_string)
Quickstart
from typed_ast import ast3
code_to_parse = """
def example_function(a: int, b) -> str:
result = a + int(b) # type: ignore
return str(result)
"""
try:
tree = ast3.parse(code_to_parse)
print("Successfully parsed code with type comments.")
# You can then traverse the AST, for example:
# import ast
# print(ast.dump(tree, indent=4))
except SyntaxError as e:
print(f"Syntax error during parsing: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")