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.
test():\n"""This is a test"""
, one can access it viatest.__doc__
. I have to assume that this is what the Python tooling uses to grab the docstrings. I want to know how to do that for type aliases defined using thetype
keyword. – Iconologytype
statement. – Iconology__doc__
attribute is present. What you state isn't completely correct though, as Python keeps a lot of__doc__
attributes for things other than modules, classes, and functions. It just handles them all differently. For example,NamedTuple
fields have a__doc__
attribute at runtime, it's just not what you would expect if you've provided a docstring. So by associate, I mean__doc__
is present and what you'd expect, which is basically what Pylance/Pyright does. – Iconology__doc__
attribute in the course of an arbitrary assignment statement. It does so forclass
statements,def
statements, and modules. Named-tuple fields are handled specially by the definition ofnamedtuple
itself (i.e.,__doc__
attributes are explicitly defined during the creation of the type.) – Scot