Skip to content

gh-85668: Add typing.evaluate_type() function#150363

Open
Viicos wants to merge 1 commit into
python:mainfrom
Viicos:gh-85668
Open

gh-85668: Add typing.evaluate_type() function#150363
Viicos wants to merge 1 commit into
python:mainfrom
Viicos:gh-85668

Conversation

@Viicos
Copy link
Copy Markdown
Contributor

@Viicos Viicos commented May 24, 2026

As per the discussion in https://discuss.python.org/t/100698.

With the new stuff since 3.14, we end up in a bit of an unfortunate situation, where we already have typing.evaluate_forward_ref() as a public function that can do pretty much anything, expect it requires a forward ref instance. So with this PR we end up with the chain evaluate_type() which is like evaluate_forward_ref() but allows arbitrary type hints, and evaluate_forward_ref() being like annotationlib.ForwardRef.evaluate() but also recursively evaluates nested forward references; this may be a bit confusing for users.

Once we agree on the expected behavior and signature for this new function, I'll add tests (wondering if I should keep the scope narrow, _eval_type() is already extensively tested by get_type_hints()) and flesh out the code docstring of the function.

@read-the-docs-community
Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #32831396 | 📁 Comparing 7275d8d against main (43c60ec)

  🔍 Preview build  

2 files changed
± library/typing.html
± whatsnew/changelog.html

Comment thread Lib/typing.py
)


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.

Comment thread Doc/library/typing.rst
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..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant