sphinx-autodoc-typehints: Python type hint: NameError: name '...' is not defined

Usecase:

class Foo(object):
    def __init__(self):
        pass
    
    def get_foo(self, name:str) -> 'Foo' :
        return self

The above is a simple example of the issue I am facing. Python type hints supports ’ ’ to be used when the class is not defined and will be defined at a later stage. Sphinx documentation using your extension fails because Foo is not defined.

Note: I have also tried adding a __main__ method, thinking it might stop auto-execution, but I ended up having the same error.

Stacktrace

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 17

Most upvoted comments

Well…it is a fixable problem but it needs to be fixed in Sphinx’s autodoc itself. The offending code is in autodoc.py, lines 370-371:

    introspected_hints = (typing.get_type_hints(function)
                          if typing and hasattr(function, '__code__') else {})

This fails because the global namespace of the wrapper does not contain the globals from the original function. What is needed is to call get_type_hints(obj, original.__globals__) where original is the unwrapped function.

On second thought, this may be a fixable problem, caused by the use of any wrapping decorator.