sphinx-autodoc-typehints icon indicating copy to clipboard operation
sphinx-autodoc-typehints copied to clipboard

get_annotation_class_name() not always returning string

Open cas-- opened this issue 3 years ago • 1 comments

We encountered the following error while setting a return type which mocked in Sphinx config using a custom Mock object

Handler <function process_docstring at 0x7f6c16c8ec10> for event 'autodoc-process-docstring' threw an exception (exception: getattr(): attribute name must be string)

The actual exception is raised in get_annotation_args in this line due to a class_name not being str:

original = getattr(sys.modules[module], class_name)

Looking further into PR #145 was opened to track this issue as they also found that get_annotation_class_name is not always retuning a str but it seems was never fixed.

A quick example to show how the custom Mock does not return str for __qualname__ or _name attributes:

>>> class Mock:
    __all__ = []
    def __init__(self, *args, **kwargs):
        pass
    def __call__(self, *args, **kwargs):
        return ''
    @classmethod
    def __getattr__(cls, name):
        return Mock()
    def __add__(self, other):
        return other
    def __or__(self, __):
        return Mock()
>> Mock()
<__main__.Mock object at 0x7f22528baf40>
>>> m =Mock()
>>> m.__qualname__
<class '__main__.__qualname__'>
>>> m._name
<class '__main__._name'>
>>> getattr(m, m.__qualname__)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: getattr(): attribute name must be string

We can workaround the issue by not using the custom mock any more but it is still an inconvenience

cas-- avatar Feb 15 '22 11:02 cas--

A PR to fix this would be welcome 👍

gaborbernat avatar Feb 16 '22 09:02 gaborbernat