Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3727,6 +3727,24 @@ Introspection helpers

.. versionadded:: 3.14

.. function:: evaluate_type(type_hint, *, owner=None, globals=None, locals=None, type_params=None, format=annotationlib.Format.VALUE)

Evaluate a :term:`type hint`, by resolving any forward references nested
within the type hint.

This is similar to calling :func:`evaluate_forward_ref`, but unlike that
method, :func:`evaluate_type` also supports arbitrary type hints.

See the documentation for :meth:`annotationlib.ForwardRef.evaluate` for
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can also properly document the behavior of each argument here, but this will introduce some repetition..

the meaning of the *owner*, *globals*, *locals*, *type_params*, and *format* parameters.

.. caution::

This function may execute arbitrary code contained the type hint.
See :ref:`annotationlib-security` for more information.

.. versionadded:: next

.. data:: NoDefault

A sentinel object used to indicate that a type parameter has no default
Expand Down
18 changes: 18 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1051,6 +1051,24 @@ def evaluate_forward_ref(
)


def evaluate_type(
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we allow plain strings to be passed, by using _make_forward_ref()? If so, what should we use for is_argument and is_class? I'd suggest we can infer the object type from owner, and if globals/locals/type params are manually provided instead, we pass is_argument=False, is_class=True as we can't assume anything on the owner and so we allow any type qualifier.

type_hint,
*,
owner=None,
globalns=None,
localns=None,
type_params=None,
format=annotationlib.Format.VALUE,
):
"""Evaluate a type hint, by resolving any forward references.

This is similar to the evaluate_forward_ref() method, but unlike that method,
evaluate_type() also supports arbitrary type hints.
"""

return _eval_type(type_hint, owner=owner, globalns=globalns, localns=localns, type_params=type_params, format=format)


def _is_unpacked_typevartuple(x: Any) -> bool:
# Need to check 'is True' here
# See: https://github.com/python/cpython/issues/137706
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add :func:`typing.evaluate_type` function.
Loading