diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 44b537f1669e1a..e74b0407b5d49b 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -1610,6 +1610,14 @@ Functions and decorators Introspection helpers --------------------- +.. function:: eval_type(t, globalns=None, localns=None) + + Evaluate the given type ``t`` by resolving any forward references. + + For usage of ``globalns`` and ``localns`` see :func:`get_type_hints`. + + .. versionadded:: 3.10 + .. function:: get_type_hints(obj, globalns=None, localns=None, include_extras=False) Return a dictionary containing type hints for a function, method, module @@ -1693,4 +1701,3 @@ Constant (see :pep:`563`). .. versionadded:: 3.5.2 - diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 7f96aff7104551..299148a9c5c917 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -13,7 +13,7 @@ from typing import Tuple, List, Dict, MutableMapping from typing import Callable from typing import Generic, ClassVar, Final, final, Protocol -from typing import cast, runtime_checkable +from typing import cast, eval_type, runtime_checkable from typing import get_type_hints from typing import get_origin, get_args from typing import no_type_check, no_type_check_decorator @@ -4175,6 +4175,19 @@ def test_annotated_in_other_types(self): self.assertEqual(X[int], List[Annotated[int, 5]]) +class EvalTypeTests(BaseTestCase): + def test_simple_reference(self): + self.assertIs(eval_type(str), str) + + def test_forward_reference(self): + self.assertIs(eval_type(ForwardRef('int')), int) + + class C: + pass + + self.assertIs(eval_type(ForwardRef('C'), localns=locals()), C) + + class AllTests(BaseTestCase): """Tests for __all__.""" diff --git a/Lib/typing.py b/Lib/typing.py index 5da032bbee8f1e..a261feb5c2323e 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -99,6 +99,7 @@ # One-off things. 'AnyStr', 'cast', + 'eval_type', 'final', 'get_args', 'get_origin', @@ -1278,6 +1279,13 @@ def cast(typ, val): return val +def eval_type(t, globalns=None, localns=None): + """Evaluate all forward references in the given type t. + For use of globalns and localns see the docstring for get_type_hints(). + """ + return _eval_type(t, globalns, localns) + + def _get_defaults(func): """Internal helper to extract the default arguments, by name.""" try: