Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #8099: autodoc: NameError is raised when script uses TYPE_CHECKING #8108

Merged
merged 2 commits into from Aug 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES
Expand Up @@ -48,6 +48,7 @@ Bugs fixed
class
* #8091: autodoc: AttributeError is raised on documenting an attribute on Python
3.5.2
* #8099: autodoc: NameError is raised when target code uses ``TYPE_CHECKING``
* C++, fix parsing of template template paramters, broken by the fix of #7944

Testing
Expand Down
6 changes: 6 additions & 0 deletions sphinx/ext/autodoc/__init__.py
Expand Up @@ -1608,6 +1608,9 @@ def add_directive_header(self, sig: str) -> None:
# obtain annotation for this data
try:
annotations = get_type_hints(self.parent)
except NameError:
# Failed to evaluate ForwardRef (maybe TYPE_CHECKING)
annotations = safe_getattr(self.parent, '__annotations__', {})
except TypeError:
annotations = {}
except KeyError:
Expand Down Expand Up @@ -1984,6 +1987,9 @@ def add_directive_header(self, sig: str) -> None:
# obtain type annotation for this attribute
try:
annotations = get_type_hints(self.parent)
except NameError:
# Failed to evaluate ForwardRef (maybe TYPE_CHECKING)
annotations = safe_getattr(self.parent, '__annotations__', {})
except TypeError:
annotations = {}
except KeyError:
Expand Down
8 changes: 8 additions & 0 deletions tests/roots/test-ext-autodoc/target/TYPE_CHECKING.py
@@ -0,0 +1,8 @@
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from io import StringIO


class Foo:
attr1: "StringIO"
22 changes: 22 additions & 0 deletions tests/test_ext_autodoc.py
Expand Up @@ -1740,6 +1740,28 @@ def test_autodoc_Annotated(app):
]


@pytest.mark.skipif(sys.version_info < (3, 6), reason='py36+ is required.')
@pytest.mark.sphinx('html', testroot='ext-autodoc')
def test_autodoc_TYPE_CHECKING(app):
options = {"members": None,
"undoc-members": None}
actual = do_autodoc(app, 'module', 'target.TYPE_CHECKING', options)
assert list(actual) == [
'',
'.. py:module:: target.TYPE_CHECKING',
'',
'',
'.. py:class:: Foo()',
' :module: target.TYPE_CHECKING',
'',
'',
' .. py:attribute:: Foo.attr1',
' :module: target.TYPE_CHECKING',
' :type: StringIO',
'',
]


@pytest.mark.sphinx('html', testroot='pycode-egg')
def test_autodoc_for_egged_code(app):
options = {"members": None,
Expand Down