Skip to content

Commit

Permalink
Fixes typing guard inside classes
Browse files Browse the repository at this point in the history
  • Loading branch information
thepabloaguilar committed Jan 18, 2022
1 parent 01b3a1a commit 2f08dcd
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/sphinx_autodoc_typehints/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,12 @@ def _resolve_type_guarded_imports(obj: Any) -> None:
for (_, part) in _TYPE_GUARD_IMPORT_RE.findall(module_code):
guarded_code = textwrap.dedent(part)
try:
exec(guarded_code, obj.__globals__)
# Some objects doesn't have the `__globals__` attribute like
# classes, so we need to check before trying to access it.
if hasattr(guarded_code, "__globals__"):
exec(guarded_code, obj.__globals__)
else:
exec(guarded_code)
except Exception as exc:
_LOGGER.warning(f"Failed guarded type import with {exc!r}")

Expand Down
9 changes: 9 additions & 0 deletions tests/roots/test-resolve-typing-guard/demo_typing_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ def a(f: Decimal, s: AnyStr) -> Sequence[AnyStr | Decimal]:
return [f, s]


class SomeClass:
"""This class do something."""

if TYPE_CHECKING: # Classes doesn't have `__globals__` attribute

def __getattr__(self, attrname: str):
"""This method do something."""


__all__ = [
"a",
"ValueError",
Expand Down

0 comments on commit 2f08dcd

Please sign in to comment.