We currently have two functions in the stdlib to evaluate type hints: typing.get_type_hints() and annotationlib.get_annotations().
These two functions expect a function, module or class object to be passed, and so it is currently not possible to evaluate a bare annotation expression. As I mentioned here, it would be useful for a couple reasons:
- When evaluating annotations for a class/function (using the
Format.VALUEformat), it is not possible to track which annotated attribute/function parameter failed to have its annotation evaluated. For runtime type checkers, this can be useful to indicate to end users where they should look to fix the error. - Several runtime type checkers provide the ability to validate data against a bare annotation expression (trycast, Pydantic’s
TypeAdapter).
I think it would be valuable to have a typing.evaluate_type() public function in the stdlib (or at least in typing-extensions):
def evaluate_type(
t,
globalns=None,
localns=None,
format=None,
owner=None,
):
return _eval_type(t, globalns, localns, type_params=(), format=format, owner=owner)
That would delegate to the existing private _eval_type() function (already relied on relatively heavily).
To be determined:
- should
type_paramsbe added as a parameter? - here’s ongoing work for this already: gh-85668: Create public API for typing._eval_type by Dominik1123 · Pull Request #21753 · python/cpython · GitHub. It was questioned whether
globalns/localnsshould have a default value. I think with the introduction ofownerin 3.14, we can make them optional.