Skip to main content

An extension to Sphinx :code:`autodoc` to augment Sphinx documentation with type annotations, when using Python 2 style type annotations.

Project description

An extension to Sphinx autodoc to augment Sphinx documentation with type annotations, when using Python 2 style type annotations.

The Problem

Python 2 doesn’t support type annotations. Thus writing Python 2 / Python 3 agnostic code with type annotations requires putting the type annotations in comments:

def add(x, y):
    # type: (int, int) -> int
    """Adds two numbers."""
    return x + y

But now when documentation is generated with Sphinx, the documentation doesn’t include type annotations:

Example from the Signatory project.

The Solution

This extension remedies things so that the Sphinx documentation now looks like:

(which is the same as what you’d get using Python 3 style type annotations e.g. def add(x: int, y: int) -> int)


Via pip:

pip install py2annotate

It’s also just a single file, so copy-paste the code if you want.

Requires Python 3.6+.


Just add py2annotate to the list of extensions in

extensions = ['sphinx.ext.autodoc', 'py2annotate']

(It shouldn’t matter whether it comes before or after autodoc.)

Note that Sphinx itself must be run using Python 3.6+. This is because py2annotate uses the Python 3 style type annotations internally in order to determine the correct annotations.

Known Issues

None so far! File a report if you run into anything. mypy and stubgen are used internally though, so your code’s formatting must be in a manner that they understand.

Download files

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

Files for py2annotate, version 1.1.1
Filename, size File type Python version Upload date Hashes
Filename, size py2annotate-1.1.1-py3-none-any.whl (4.5 kB) File type Wheel Python version py3 Upload date Hashes View

Supported by

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