Today I’ve started updating to Python 3.12 and adapted my code base to use the new typing aliases defined in PEP 695.
Previously, my type was defined as
CustomType = dict[str, int] with a docstring below using multine strings.
Using the new type alias syntax, this was converted to
type CustomType = dict[str, int]. I’ve then discovered that both pylint complains about the following multiline (doc)string (
pointless-string-statement, also filed an issue) and my editor (VS Code) does not display the docstring on hover.
I’ve then went ahead and tried multiple different ways of adding a docstring (single line string above/below,
#: comment above / below, regular comment above / below) but none of them worked.
How do I properly document my type aliases using the new syntax?
I have the exact same question, as asked on StackOverflow today: How do I document a type alias defined using `type` in Python? - Stack Overflow
Since the PEP doesn’t mention it, it doesn’t seem promising that support was added for this, which is unfortunate if that’s the case.
Docstrings for assignments aren’t part of the standard Python syntax; support in tools like Sphinx is just a convention. I would recommend tools apply the same convention to the
type statement that they apply to existing old-style alias definitions.
As Jelle said, there is currently no standardized way to provide documentation for type aliases.
There is a draft PEP 727 that proposed to add such support, but the latest version of the PEP removes the support for type alias doc strings. Plus, there’s a lot of community pushback on this PEP, so its future is unclear.
That said, pyright (which is presumably what you’re using to power your editor experience) currently supports the convention of interpreting multi-line strings below a type alias definition as a doc string. It would make sense to extend that support to
type statements. I just didn’t think to add this when I added support for PEP 695. I’ve added this enhancement request in the pyright issue tracker.
I’ll note that this isn’t currently standardized, so other type checkers, language servers, and static analysis tools may not honor this.
I’ve added support for
type statement doc strings within pyright. It will be included in the next pyright release. It will also be in a future release of Pylance, the default Python language server for VS Code.
Understood, thanks for your answers and the quick fix for pyright / pylance. I’ll forward this information to the tools I’ve encountered issues with.