python - 如何使用 python 的结构模式匹配来测试内置类型?

标签 python python-3.10 structural-pattern-matching

我正在尝试使用 SPM 来确定某个 typeint 还是 str

以下代码:

from typing import Type

def main(type_to_match: Type):
    match type_to_match:
        case str():
            print("This is a String")
        case int():
            print("This is an Int")
        case _:
            print("\nhttps://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg")

if __name__ == "__main__":
    test_type = str
    main(test_type)

返回 https://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg

我发现的大多数文档都讨论了如何测试某个变量是否是某个类型的实例。但不是如何测试一个类型是否属于某种类型。

关于如何使它工作的任何想法?

最佳答案

如果你只是直接传递一个类型,它会认为它是“名称捕获”而不是“值捕获”。您可以通过导入 builtins 模块并使用点分符号来检查类型来强制它使用值捕获。

import builtins
from typing import Type


def main(type_: Type):
    match (type_):
        case builtins.str:  # it works with the dotted notation
            print(f"{type_} is a String")
        case builtins.int:
            print(f"{type_} is an Int")
        case _:
            print("\nhttps://en.meming.world/images/en/0/03/I%27ve_Never_Met_This_Man_In_My_Life.jpg")

if __name__ == "__main__":
    main(type("hello"))  # <class 'str'> is a String
    main(str)  # <class 'str'> is a String
    main(type(42))  # <class 'int'> is an Int
    main(int)  # <class 'int'> is an Int

关于python - 如何使用 python 的结构模式匹配来测试内置类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70862692/

相关文章:

python - Opencv 将 numpy.zeros 绘制为灰度图像

python - 导入不规则大小的文本文件

python - 通过组合元组元素获取元组列表的产品?

c++ - 在客户的计算机上搜索特定文件

Python 3.10 类型提示导致语法错误

python - Python结构模式匹配中如何区分元组和列表?

python - 捕获使剩余模式无法访问

python - 为什么下划线在新的 Python 匹配中不是有效名称?

python - 如何用结构模式匹配来表达 hasattr() 鸭子类型(duck typing)逻辑?