Skip to content

Commit

Permalink
Add sphinx.util.inspect:isgenericalias()
Browse files Browse the repository at this point in the history
  • Loading branch information
tk0miya committed May 30, 2020
1 parent 9988d5c commit e20f29e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
13 changes: 13 additions & 0 deletions sphinx/util/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import inspect
import re
import sys
import types
import typing
import warnings
from functools import partial, partialmethod
Expand Down Expand Up @@ -304,6 +305,18 @@ def isproperty(obj: Any) -> bool:
return isinstance(obj, property)


def isgenericalias(obj: Any) -> bool:
"""Check if the object is GenericAlias."""
if (hasattr(typing, '_GenericAlias') and # only for py37+
isinstance(obj, typing._GenericAlias)): # type: ignore
return True
elif (hasattr(types, 'GenericAlias') and # only for py39+
isinstance(obj, types.GenericAlias)): # type: ignore
return True
else:
return False


def safe_getattr(obj: Any, name: str, *defargs: Any) -> Any:
"""A getattr() that turns all exceptions into AttributeErrors."""
try:
Expand Down
6 changes: 6 additions & 0 deletions tests/roots/test-ext-autodoc/target/genericalias.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from typing import List, Callable

#: A list of int
T = List[int]

C = Callable[[int], None] # a generic alias not having a doccomment
12 changes: 12 additions & 0 deletions tests/test_util_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,18 @@ def test_isproperty(app):
assert inspect.isproperty(func) is False # function


@pytest.mark.skipif(sys.version_info < (3, 7), reason='python 3.7+ is required.')
@pytest.mark.sphinx(testroot='ext-autodoc')
def test_isgenericalias(app):
from target.genericalias import C, T
from target.methods import Base

assert inspect.isgenericalias(C) is True
assert inspect.isgenericalias(T) is True
assert inspect.isgenericalias(object()) is False
assert inspect.isgenericalias(Base) is False


def test_unpartial():
def func1(a, b, c):
pass
Expand Down

0 comments on commit e20f29e

Please sign in to comment.