【问题标题】:how to fix TypeError: called match pattern must be a type in Python 3.10如何修复 TypeError:调用的匹配模式必须是 Python 3.10 中的类型
【发布时间】:2021-11-10 18:43:50
【问题描述】:

尝试学习 Python 3.10 模式匹配。阅读8.6.4.9. Mapping Patterns后尝试了这个例子

>>> match 0.0:
...  case int(0|1):
...   print(1)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: called match pattern must be a type
>>>

特别是关于内置类型的注释,包括 int。我应该如何编写代码来测试整数值 0 或 1(文档中的示例)而不出现此错误?

【问题讨论】:

  • 我无法重现该错误。在 Python 3.10 控制台上执行您的确切行不会打印任何内容。然后,将 0.0 更改为 0 或 1 打印 1。我不确定您是如何得到该错误的,您的代码应该可以正常工作。

标签: pattern-matching python-3.10


【解决方案1】:

对于结构模式匹配,类模式需要在类名两边加上括号。

例如:

x = 0.0
match x:
    case int():
        print('I')
    case float():
        print('F')
    case _:
        print('Other')

【讨论】:

    【解决方案2】:

    我陷入了困境:

    match 0.0
      case int:
        print(1)
    

    有效地重新定义了 int,所以下次我尝试我发布的匹配时,它失败了,因为 my int 隐藏了内置

    【讨论】:

      【解决方案3】:

      我应该如何编写代码来测试整数值 0 或 1

      正确的答案是使用OR-Patterns,在PEP 622中描述:

      可以使用 | 将多个替代模式组合为一个。这 表示如果至少有一个替代匹配,则整个模式匹配。 从左到右尝试替代方案并短路 属性,如果一个匹配,则不会尝试后续模式。

      x = 1
      match x:
          case int(0 | 1):
              print('case of x = int(0) or x = int(1)')
          case _:
              print('x != 1 or 0')
      

      输出:'x = int(0) 或 x = int(1) 的情况'

      类型不敏感会是这样的:

      x = 1.0
      match x:
          case 0 | 1:
              print('case of x = 0 or x = 1')
          case _:
              print('x != 1 or 0')
      

      输出:'x = 0 或 x = 1 的情况'


      如果您想分别检查每个案例,您可以:

      x = 1.0
      match x:
          case int(0):
              print('x = 0')
          case int(1):
              print('x = 1')
          case _:
              print('x != 1 or 0')
      

      输出:x != 1 or 0

      x = 1.0
      match x:
          case 0:
              print('x = 0')
          case 1:
              print('x = 1')
          case _:
              print('x != 1 or 0')
      

      输出:x = 1

      【讨论】:

        猜你喜欢
        • 2022-12-19
        • 1970-01-01
        • 2019-11-15
        • 2019-08-19
        • 2023-01-13
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多