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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With