You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ClassVar as string fails when getting type hints #505
I know there are plans to make all type annotations strings eventually. So I was playing around and discovered this problem.
import typing
class Good:
foo: typing.ClassVar[int] = 7
print(typing.get_type_hints(Good))
class Bad:
foo: 'typing.ClassVar[int]' = 7
typing.get_type_hints(Bad)
{'foo': typing.ClassVar[int]}
Traceback (most recent call last):
File "classvar_problem.py", line 10, in <module>
typing.get_type_hints(Bad)
File "/usr/local/homebrew/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/typing.py", line 1511, in get_type_hints
value = _eval_type(value, base_globals, localns)
File "/usr/local/homebrew/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/typing.py", line 350, in _eval_type
return t._eval_type(globalns, localns)
File "/usr/local/homebrew/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/typing.py", line 246, in _eval_type
"Forward references must evaluate to types.")
File "/usr/local/homebrew/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/typing.py", line 374, in _type_check
raise TypeError(msg + " Got %.100r." % (arg,))
TypeError: Forward references must evaluate to types. Got typing.ClassVar[int].
Thanks! This is an interesting edge case. ClassVar[int] is not valid as a type argument, so currently for example List[ClassVar[int]] raises TypeError, and we re-use the same internal helper that checks this in get_type_hints (which is apparently wrong).
We will probably just remove this check soon, so that the errors like this will be reported only in type checkers (like mypy), but not at runtime.
Activity
ilevkivskyi commentedon Nov 26, 2017
Thanks! This is an interesting edge case.
ClassVar[int]is not valid as a type argument, so currently for exampleList[ClassVar[int]]raisesTypeError, and we re-use the same internal helper that checks this inget_type_hints(which is apparently wrong).We will probably just remove this check soon, so that the errors like this will be reported only in type checkers (like mypy), but not at runtime.
Declaring a ClassVar with a type as a string shouldn't fail at runtim…