Skip to content

ClassVar as string fails when getting type hints #505

Closed
python/cpython
#6824

Description

@euresti

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].

Activity

  1. ilevkivskyi commented on Nov 26, 2017

    @ilevkivskyi
    Member

    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.

  2. self-assigned this
    on May 14, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions