typing_extensions
typing_extensions copied to clipboard
Backport support for get_type_hints on lone stringified ClassVar
Currently, both typing.get_type_hints and typing_extensions.get_type_hints fail on a lone stringified ClassVar annotation in Python 3.9 and 3.10:
from __future__ import annotations
from typing import ClassVar, get_type_hints as get_type_hints
from typing_extensions import get_type_hints as get_type_hints_ext
class Foo:
MY_CLASS_CONSTANT: ClassVar = 5
try:
_ = get_type_hints(Foo)
except TypeError as exc:
print(exc)
try:
_ = get_type_hints_ext(Foo)
except TypeError as exc:
print(exc)
This is unfortunate, as https://github.com/python/cpython/issues/90711 addressed this for Python 3.11+, so it would be nice if typing-extensions backported this fix for older python versions.
For reference this is the stack trace on 3.10:
>>> get_type_hints(Foo)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jelle/.local/share/uv/python/cpython-3.10.16-macos-aarch64-none/lib/python3.10/typing.py", line 1833, in get_type_hints
value = _eval_type(value, base_globals, base_locals)
File "/Users/jelle/.local/share/uv/python/cpython-3.10.16-macos-aarch64-none/lib/python3.10/typing.py", line 327, in _eval_type
return t._evaluate(globalns, localns, recursive_guard)
File "/Users/jelle/.local/share/uv/python/cpython-3.10.16-macos-aarch64-none/lib/python3.10/typing.py", line 693, in _evaluate
type_ = _type_check(
File "/Users/jelle/.local/share/uv/python/cpython-3.10.16-macos-aarch64-none/lib/python3.10/typing.py", line 171, in _type_check
raise TypeError(f"Plain {arg} is not valid as type argument")
TypeError: Plain typing.ClassVar is not valid as type argument
Fixing this likely requires duplicating much of that call stack.