GeezerVison is showing github.com — Confusing error message when attempting to pass a newtype as a match pattern · Issue #100530 · python/cpython
Confusing error message when attempting to pass a newtype as a match pattern #100530Descriptionfrom typing import NewType
T = NewType('T', str)
match 'test':
case T(): ...
fails with:
Traceback (most recent call last):
File "/tmp/foo.py", line 6, in <module>
case T(): ...
^^^
TypeError: called match pattern must be a type
The error message is confusing because T is a type. The error message should probably say class instead of type, since as per the specification it's a class pattern.
Linked PRs
ActivityAlexWaygood commented on Dec 26, 2022 brandtbucher commented on Dec 27, 2022 Hm... I'm not really sure there's anything to do here. I think the main issue is Python's general overloading of the word "type" to refer to both static types (for annotations) and types of objects. It's this second group that we're checking for here:
>>> import typing
>>> T = typing.NewType("T", str)
>>> isinstance(T, type)
False
With that said, I'm open to changing the wording of the error message from "type" to "class" if others agree that the current wording is confusing. Reacted by Martin Fischer sobolevn commented on Apr 16, 2023 I agree that class is a much better term here than type. Because, here's one more example where type is not quite correct:
>>> import typing
>>> A = typing.Annotated[str, 'meta']
>>> match 'abc':
... case A(): ...
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: called match pattern must be a type
typing.Annotated[str, 'meta'] is a type. But it is not a class.
Moreover, the ast node is also called MatchClass which is another argument for the wording change.
Reacted by Terry Jan Reedy and Peter Zaitcev / [USSX] Hares
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|