用于检查协议的模式匹配。获取类型错误:调用的匹配模式必须是类型
我需要匹配输入可迭代的情况。这是我尝试过的:
from typing import Iterable
def detector(x: Iterable | int | float | None) -> bool:
match x:
case Iterable():
print('Iterable')
return True
case _:
print('Non iterable')
return False
这会产生此错误:
TypeError: called match pattern must be a type
Is it possible to detector iterability with match/case?
请注意,这两个问题解决了相同的错误消息,但两个问题都不是关于如何检测可迭代性:
I need to match cases where the input is iterable. Here's what I tried:
from typing import Iterable
def detector(x: Iterable | int | float | None) -> bool:
match x:
case Iterable():
print('Iterable')
return True
case _:
print('Non iterable')
return False
That is producing this error:
TypeError: called match pattern must be a type
Is it possible to detect iterability with match/case?
Note, these two questions address the same error message but neither question is about how to detect iterability:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是 typing.Iterable 仅适用于 类型提示,并且不被结构模式匹配视为“类型”。相反,您需要使用抽象基类检测可迭代性:collections.abc.Iterable。
解决方案是区分这两种情况,将一种标记为类型提示,另一种标记为结构模式匹配的类模式:
另请注意,在撰写本文时 mypy 不支持 匹配语句。
The problem is the typing.Iterable is only for type hints and is not considered a "type" by structural pattern matching. Instead, you need to use an abstract base class for detecting iterability: collections.abc.Iterable.
The solution is distinguish the two cases, marking one as being a type hint and the other as a class pattern for structural pattern matching:
Also note that at the time of this writing mypy does not support the match statement.