[issue42377] allow typing.cast with TYPE_CHECKING
Ken Jin
report at bugs.python.org
Fri Jan 15 12:05:35 EST 2021
Ken Jin <kenjin4096 at gmail.com> added the comment:
Sorry, I don't think this is a typing module issue.
The NameError stems from what you mentioned: 'A' not being defined since TYPE_CHECKING evaluates to false at runtime. This would raise an error in any Python code, not just typing. The equivalent is this::
>>> A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined
Without the future import, def f(a: A): ... already throws that NameError. The reason why it works in your example is because 'A' isn't evaluated at function declaration time with the future import.
To appease your static type checker and not cause runtime errors, you might want to try:
f(cast("A", "anything"))
Which seems to work in mypy and pycharm. (Sorry, I don't have pyre/pytype/pyright to check with, though I would be surprised if this didn't pass on them.)
Please correct me if you feel anything I wrote was incorrect :).
----------
nosy: +gvanrossum, kj, levkivskyi
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42377>
_______________________________________
More information about the Python-bugs-list
mailing list