3

Recently I wanted to reuse doc-sting of class attributes to make some user-friendly self-description but could not find a way to access a doc-string of the attribute of the class.

Consider example:

>>> class Foo(object):
...     """I am a doc-string of the foo class"""    
...     bar: int = 42
...     """I am a doc-string of the bar attribute"""
...     
>>> Foo.__doc__
'I am a doc-string of the foo class'
>>> Foo.bar.__doc__
"int([x]) -> integer\nint(x, base=10) -> integer\n\nConvert a number or string to an integer, or return 0 if no arguments\nare given.  If x is a number, return x.__int__().  For floating point\nnumbers, this truncates towards zero.\n\nIf x is not a number or if base is given, then x must be a string,\nbytes, or bytearray instance representing an integer literal in the\ngiven base.  The literal can be preceded by '+' or '-' and be surrounded\nby whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.\nBase 0 means to interpret the base from the string as an integer literal.\n>>> int('0b100', base=0)\n4"

Accessing doc-sting of an attribute of the class give a docstring of the annotated type.

Is it even possible at all, preferably without extra libarries or imports?

kuza
  • 2,761
  • 3
  • 22
  • 56
  • Not exactly a duplicate, as a question not about how to document but how to access already documented. Yet referenced question in one of the answers quotes [PEP-0258](https://www.python.org/dev/peps/pep-0258/#attribute-docstrings) that states why it is not possible. – kuza Apr 14 '19 at 07:05

1 Answers1

3

Unfortunately it doesn’t seems possible.

An existing PEP-0258 in “Additional Docstrings” sections explains that doc-string on classes’ attributes are not retained in the runtime.

Many programmers would like to make extensive use of docstrings for API documentation. However, docstrings do take up space in the running program, so some programmers are reluctant to "bloat up" their code. Also, not all API documentation is applicable to interactive environments, where doc would be displayed.

Docutils' docstring extraction tools will concatenate all string literal expressions which appear at the beginning of a definition or after a simple assignment. Only the first strings in definitions will be available as doc, and can be used for brief usage text suitable for interactive sessions; subsequent string literals and all attribute docstrings are ignored by the Python byte-code compiler and may contain more extensive API information.

kuza
  • 2,761
  • 3
  • 22
  • 56