python Python PEPs ·

PEP 846 Proposes Docstrings for Python Type Aliases

engineer
feature

PEP 846 proposes a new feature for Python 3.16, enabling `type` aliases to have docstrings accessible via their `__doc__` attribute. This change aims to improve discoverability and documentation for type aliases, allowing tools like `pydoc` and `help()` to display explanatory text directly from the alias object. The proposal standardizes a convention already adopted by several development tools, benefiting developers and framework authors who leverage Python's typing system. It outlines specifications for docstring placement, runtime behavior, and AST support.

  • Introduce Docstrings for Type Aliases
  • Runtime Access and Tooling Support
  • AST and Compilation Changes
Features (1)
  • Introduce Docstrings for Type Aliases

    PEP 846 proposes preserving a string literal immediately following a `type` statement as the resulting type alias object’s `__doc__` attribute. This standardizes a placement convention already supported by source-based documentation tools like Pyright, Sphinx, and Pylint. The rule applies wherever a type statement is allowed, including inside functions, classes, and generic aliases.

Enhancements (1)
  • Runtime Access and Tooling Support

    The docstring will be accessible at runtime through the alias's `__doc__` attribute, enabling tools like `pydoc` and `help()` to display it, rather than generic `TypeAliasType` information. This makes documentation available directly from the imported alias, benefiting third-party frameworks that can consume `__doc__` as descriptive metadata. The `TypeAliasType` constructor will also gain a `doc` parameter for initialization.

Maintenance (1)
  • AST and Compilation Changes

    The `ast.TypeAlias` node will gain an optional `doc` field to store the docstring, which `ast.get_docstring()` will retrieve, with default cleaning by `inspect.cleandoc()`. Docstrings will be stripped at optimization level 2 (via `-OO`), similar to function and class docstrings, but retained at levels 0 and 1. `ast.unparse()` will emit the docstring as a string statement on the line after the alias.

Read the original announcement →

https://peps.python.org/pep-0846/

Related releases