Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I document a type alias defined using `type` in Python?

Python 3.12 has the type statement. How do I document the type alias properly?

I tried:

type Number = int | float
"""Represents a scalar number that is either an integer or float"""

But this doesn't seem to associate the docstring with the alias. I tried putting the docstring after the = and before the alias definition, but that generated an error.

like image 770
bmitc Avatar asked May 03 '26 06:05

bmitc


1 Answers

I think there is no direct way. For classes, functions and methods, if the first statement is a string, the string is added to the __doc__ attribute of the class/method/function.

So for example:

def foo():
    "Docstring"

is for the runtime the same as:

def foo():
    pass
foo.__doc__ = "Docstring"

Because the TypeAliasType definition lacks the implicit __doc__ setting, I tried to do it explicitly:

type Number = int | float
Number.__doc__ = "Docstring"

which results in the following error:

AttributeError: 'typing.TypeAliasType' object attribute 'doc' is read-only

I think there is no supported way of documentation of TypeAliasType instances. And it depends on your documentation generation tool, e.g. PyCharm or sphinx and their static code analysis, if the docstring is "related" or not.

like image 142
user23307932 Avatar answered May 04 '26 18:05

user23307932



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!