diff --git a/CHANGES b/CHANGES index 2a70ade5433..6f0e49b14cb 100644 --- a/CHANGES +++ b/CHANGES @@ -16,6 +16,9 @@ Features added Bugs fixed ---------- +* #8415: autodoc: a TypeVar imported from other module is not resolved (in + Python 3.7 or above) + Testing -------- diff --git a/sphinx/util/typing.py b/sphinx/util/typing.py index 2d4f67bba26..1e6cffdf781 100644 --- a/sphinx/util/typing.py +++ b/sphinx/util/typing.py @@ -292,7 +292,10 @@ def stringify(annotation: Any) -> str: else: return annotation elif isinstance(annotation, TypeVar): - return annotation.__name__ + if annotation.__module__ == 'typing': + return annotation.__name__ + else: + return '.'.join([annotation.__module__, annotation.__name__]) elif inspect.isNewType(annotation): # Could not get the module where it defiend return annotation.__name__ diff --git a/tests/test_util_inspect.py b/tests/test_util_inspect.py index 17070f4d6a9..5a2206c055f 100644 --- a/tests/test_util_inspect.py +++ b/tests/test_util_inspect.py @@ -142,7 +142,13 @@ def test_signature_annotations(): # TypeVars and generic types with TypeVars sig = inspect.signature(f2) - assert stringify_signature(sig) == '(x: List[T], y: List[T_co], z: T) -> List[T_contra]' + if sys.version_info < (3, 7): + assert stringify_signature(sig) == '(x: List[T], y: List[T_co], z: T) -> List[T_contra]' + else: + assert stringify_signature(sig) == ('(x: List[tests.typing_test_data.T],' + ' y: List[tests.typing_test_data.T_co],' + ' z: tests.typing_test_data.T' + ') -> List[tests.typing_test_data.T_contra]') # Union types sig = inspect.signature(f3) diff --git a/tests/test_util_typing.py b/tests/test_util_typing.py index a2565f1e1fc..c3f95abbe1c 100644 --- a/tests/test_util_typing.py +++ b/tests/test_util_typing.py @@ -184,10 +184,17 @@ def test_stringify_type_hints_typevars(): T_co = TypeVar('T_co', covariant=True) T_contra = TypeVar('T_contra', contravariant=True) - assert stringify(T) == "T" - assert stringify(T_co) == "T_co" - assert stringify(T_contra) == "T_contra" - assert stringify(List[T]) == "List[T]" + if sys.version_info < (3, 7): + assert stringify(T) == "T" + assert stringify(T_co) == "T_co" + assert stringify(T_contra) == "T_contra" + assert stringify(List[T]) == "List[T]" + else: + assert stringify(T) == "tests.test_util_typing.T" + assert stringify(T_co) == "tests.test_util_typing.T_co" + assert stringify(T_contra) == "tests.test_util_typing.T_contra" + assert stringify(List[T]) == "List[tests.test_util_typing.T]" + assert stringify(MyInt) == "MyInt"