Typed-AST

1.5.5 · maintenance · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates parsing Python 3 code containing PEP 484 type comments using `typed_ast.ast3.parse`. The `typed_ast` module was specifically designed to handle these comments, which the standard `ast` module in Python versions prior to 3.8 did not expose directly in the AST. For Python 3.8 and newer, the standard `ast` module can often be used instead.

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}")

view raw JSON →