samvv
samvv

Reputation: 2134

Is it possible to get the DocString of a typed class property in Python 3?

I'm messing with the typing module in Python 3 to see how far I can stretch it for a DSL. In order to make this DSL usable, I'd like to extract the DocStrings of some user-defined classes, like this one:

class MyRecord:
    """
    This is just a foo.

    Wouldn't it be cool if you could extract this DocString's text at runtime?
    """
    foo: str

I've been searching and found PEP 526 but it does not tell me anything about the use of DocStrings for this case. The only information I could find is on how to embed type information within a DocString, but that is not what I'm after.

FWIW, Python does not complain when feeding it the above example. However, it also does not seem to populate a __doc__ attribute, either. Am I correct in assuming this is currently not part of the standard and as such not supported?

Update: I have done a terrible job at explaining what I'm trying to achieve. I've posted an answer that contains a much better example:

class MyRecord:
    foo: str
    """
    This is a foo.
    """
    bar: str
    """
    This is a bar.
    """

As is to be expected, there is no way to access this data in the current specification. The only solution is to parse the AST and extract it from there using e.g. inspect.getsource().

Upvotes: 4

Views: 652

Answers (2)

samvv
samvv

Reputation: 2134

Ok so I was being incredibly stupid. Of course, the first DocString in the example is the class DocString, and is never associated with a method/property.

This would have been a better example:

class MyRecord:
    foo: str
    """
    This is a foo.
    """
    bar: str
    """
    This is a bar.
    """

But unfortunately this is not accessible in the current CPython implementation, and I am not sure it ever will.

Upvotes: 0

Telcrome
Telcrome

Reputation: 369

Docstrings can be extracted from any python object either with the help(obj) built-in, using inspect.get_doc(obj) or obj.__doc__.

import inspect

class MyRecord:
    """
    This is just a foo.

    Wouldn't it be cool if you could extract this DocString's text at runtime?
    """
    foo: str

>>> inspect.getdoc(MyRecord)
"This is just a foo.\n\nWouldn't it be cool if you could extract this DocString's text at runtime?"

The type hint can be read at runtime using the typing module:

(import typing)
>>> typing.get_type_hints(MyRecord)
{'foo': str}

Upvotes: 1

Related Questions