用于检查协议的模式匹配。获取类型错误:调用的匹配模式必须是类型

发布于 2025-01-10 19:31:27 字数 986 浏览 0 评论 0原文

我需要匹配输入可迭代的情况。这是我尝试过的:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅紫色的梦幻 2025-01-17 19:31:28

问题是 typing.Iterable 仅适用于 类型提示,并且不被结构模式匹配视为“类型”。相反,您需要使用抽象基类检测可迭代性:collections.abc.Iterable

解决方案是区分这两种情况,将一种标记为类型提示,另一种标记为结构模式匹配的类模式:

def detector(x: typing.Iterable | int | float | None) -> bool:
    match x:
        case collections.abc.Iterable():
            print('Iterable')
            return True
        case _:
            print('Non iterable')
            return False

另请注意,在撰写本文时 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:

def detector(x: typing.Iterable | int | float | None) -> bool:
    match x:
        case collections.abc.Iterable():
            print('Iterable')
            return True
        case _:
            print('Non iterable')
            return False

Also note that at the time of this writing mypy does not support the match statement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文