Skip to content

Commit 7275d8d

Browse files
committed
gh-85668: Add typing.evaluate_type() function
1 parent 43c60ec commit 7275d8d

3 files changed

Lines changed: 37 additions & 0 deletions

File tree

Doc/library/typing.rst

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3727,6 +3727,24 @@ Introspection helpers
37273727

37283728
.. versionadded:: 3.14
37293729

3730+
.. function:: evaluate_type(type_hint, *, owner=None, globals=None, locals=None, type_params=None, format=annotationlib.Format.VALUE)
3731+
3732+
Evaluate a :term:`type hint`, by resolving any forward references nested
3733+
within the type hint.
3734+
3735+
This is similar to calling :func:`evaluate_forward_ref`, but unlike that
3736+
method, :func:`evaluate_type` also supports arbitrary type hints.
3737+
3738+
See the documentation for :meth:`annotationlib.ForwardRef.evaluate` for
3739+
the meaning of the *owner*, *globals*, *locals*, *type_params*, and *format* parameters.
3740+
3741+
.. caution::
3742+
3743+
This function may execute arbitrary code contained the type hint.
3744+
See :ref:`annotationlib-security` for more information.
3745+
3746+
.. versionadded:: next
3747+
37303748
.. data:: NoDefault
37313749

37323750
A sentinel object used to indicate that a type parameter has no default

Lib/typing.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,6 +1051,24 @@ def evaluate_forward_ref(
10511051
)
10521052

10531053

1054+
def evaluate_type(
1055+
type_hint,
1056+
*,
1057+
owner=None,
1058+
globalns=None,
1059+
localns=None,
1060+
type_params=None,
1061+
format=annotationlib.Format.VALUE,
1062+
):
1063+
"""Evaluate a type hint, by resolving any forward references.
1064+
1065+
This is similar to the evaluate_forward_ref() method, but unlike that method,
1066+
evaluate_type() also supports arbitrary type hints.
1067+
"""
1068+
1069+
return _eval_type(type_hint, owner=owner, globalns=globalns, localns=localns, type_params=type_params, format=format)
1070+
1071+
10541072
def _is_unpacked_typevartuple(x: Any) -> bool:
10551073
# Need to check 'is True' here
10561074
# See: https://github.com/python/cpython/issues/137706
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add :func:`typing.evaluate_type` function.

0 commit comments

Comments
 (0)