我正在尝试使用 SPM 来确定某个 type 是 int
还是 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/