Skip to main content

typed-astunparse is to typed-ast as astunparse is to ast

Project description

Unparser for Python 3 abstract syntax trees (ASTs) with type comments.

package version from PyPI build status from Travis CI build status from AppVeyor grade from Codacy test coverage from Codecov license

The typed-astunparse is to typed-ast as astunparse is to ast. In short: unparsing of Python 3 abstract syntax trees (ASTs) with type comments.

Why this module was created

The built-in ast module can parse Python source code into AST but it can’t generate source code from the AST. The astunparse module (using a refactored version of an obscure script found in official Python repository) provides code generation capability for native Python AST.

However, both ast and astunparse modules completely ignore type comments introduced in PEP 484. They treat them like all other comments, so when you parse the code using compile(), your type comments will be lost. There is no place for them in the AST, so obviously they also cannot be unparsed.

The typed-ast module provides an updated AST including type comments defined in PEP 484 and a parser for Python code that contains such comments.

Unfortunately, typed-ast doesn’t provide any means to go from AST back to source code with type comments. This is why module typed-astunparse (i.e. this one) was created: to provide unparser for AST defined in typed-ast.


Example of roundtrip from code through AST to code:

import typed_ast.ast3
import typed_astunparse

code = 'my_string = None  # type: str'
roundtrip = typed_astunparse.unparse(typed_ast.ast3.parse(code))

This will print:

my_string = None  # type: str

for more examples see examples.ipynb notebook.


For simplest installation use pip:

pip3 install typed-astunparse

You can also build your own version:

git clone
cd typed-astunparse
pip3 install -U test_requirements.txt
python3 -m unittest  # make sure the tests pass
python3 bdist_wheel
pip3 install dist/*.whl


Python version 3.5 or later.

Python libraries as specified in requirements.txt.

Building and running tests additionally requires packages listed in test_requirements.txt.

Tested on Linux, OS X and Windows.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

typed-astunparse-2.1.4.tar.gz (23.3 kB view hashes)

Uploaded source

Built Distribution

typed_astunparse-2.1.4-py3-none-any.whl (14.9 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page