
On Tue, Apr 13, 2021 at 9:57 AM Larry Hastings <larry@hastings.org> wrote:
On 4/12/21 4:50 PM, Inada Naoki wrote:
PEP 563 solves all problems relating to types not accessible in runtime. There are many reasons users can not get types used in annotations at runtime:
* To avoid circular import * Types defined only in pyi files * Optional dependency that is slow to import or hard to install
It only "solves" these problems if you leave the annotation as a string. If PEP 563 is active, but you then use typing.get_type_hints() to examine the actual Python value of the annotation, all of these examples will fail with a NameError. So, in this case, "solves the problem" is a positive way of saying "hides a runtime error".
Of course, "get type which is unavailable in runtime" is unsolvable problem. PEP 597 doesn't solve it too. Author needs to quote the hint manually, and `typing.get_type_hints()` raises NameError too. And if author forget to quote, user can not get any type hints.
I don't know what the use cases are for examining type hints at runtime, so I can't speak as to how convenient or inconvenient it is to deal with them strictly as strings. But it seems to me that examining annotations as their actual Python values would be preferable.
This is use cases for examining type hints at runtime and stringified hints are OK. * Sphinx autodoc * help() * IPython and other REPLS showing type hint in popup.
``` from dataclasses import dataclass
if 0: from fakemod import FakeType
@dataclass class C: a : FakeType = 0 ```
This works on PEP 563 semantics (Python 3.10a7). User can get stringified annotation.
With stock semantics, it cause NameError when importing so author can notice they need to quote "FakeType".
With PEP 649 semantics, author may not notice this annotation cause error. User can not get any type hints at runtime.
Again, by "works on PEP 563 semantics", you mean "doesn't raise an error". But the code has an error. It's just that it has been hidden by PEP 563 semantics.
I don't agree that changing Python to automatically hide errors is an improvement. As the Zen says: "Errors should never pass silently."
This is really the heart of the debate over PEP 649 vs PEP 563. If you examine an annotation, and it references an undefined symbol, should that throw an error? There is definitely a contingent of people who say "no, that's inconvenient for us". I think it should raise an error. Again from the Zen: "Special cases aren't special enough to break the rules." Annotations are expressions, and if evaluating an expression fails because of an undefined name, it should raise a NameError.
I agree that this is the heart of the debate. I think "annotations are for type hitns". They are for: * Static type checkers * document. So I don't think `if TYPE_CHECKING` idiom is violating Python Zen. Regards, -- Inada Naoki <songofacandy@gmail.com>