如何在Python中使用守卫组合两个匹配模式

huangapple go评论101阅读模式
英文:

How to combine two match patterns with guards in Python

问题

考虑以下情况:

  1. 匹配 var1:
  2. 如果 var2 == 1 的话情况 enum.A
  3. {代码块}
  4. 如果 var2 == 2 的话情况 enum.B
  5. {代码块}
  6. ...

这里的 {代码块} 是完全相同的代码,我不想重复。

有没有一种好的方法可以在不将 {代码块} 重构为函数的情况下进行穿透或组合这两种情况?

英文:

Consider the following case:

  1. match var1:
  2. case enum.A if var2 == 1:
  3. {code block}
  4. case enum.B if var2 == 2:
  5. {code block}
  6. ...

Here {code block} is exactly the same code, which I don't want to repeat.

Is there a nice way of doing a fall-through or combining these two cases without refactoring {code block} into a function?

答案1

得分: 2

使用组合的子模式在枚举值上:

示例:

  1. from enum import Enum
  2. class E(Enum):
  3. A = 'A'
  4. B = 'B'
  5. v1 = 'B'
  6. v2 = 3
  7. match (v1, v2):
  8. case (E.A.value, 1) | (E.B.value, (2 | 3 | 4 | 5)):
  9. print('ok')
  10. case _:
  11. print('pass')

  1. ok
英文:

Use combined sub-patterns on enum values:

Sample:

  1. from enum import Enum
  2. class E(Enum):
  3. A = 'A'
  4. B = 'B'
  5. v1 = 'B'
  6. v2 = 3
  7. match (v1, v2):
  8. case (E.A.value, 1) | (E.B.value, (2 | 3 | 4 | 5)):
  9. print('ok')
  10. case _:
  11. print('pass')

  1. ok

答案2

得分: 1

你可以通过匹配元组来获得所需的效果:

  1. match (var1, var2):
  2. case (enum.A, 1) | (enum.B, 2):
  3. {代码块}
  4. ...

在评论中,你还提到:

> 如果第二个 case 是 case enum.B if var2 in {2, 3, 4, 5}: 怎么办?

在这种情况下,你可以使用嵌套模式,类似于 PEP 636 中示例所示的方式

  1. match (var1, var2):
  2. case (enum.A, 1) | (enum.B, (2 | 3 | 4 | 5)):
  3. {代码块}
  4. ...

(感谢 RomanPerekhrest 的回答,我之前不知道这个。)

英文:

You can get the desired effect by matching on tuples:

  1. match (var1, var2):
  2. case (enum.A, 1) | (enum.B, 2):
  3. {code block}
  4. ...

In a comment you additionally asked:

> What if the second case is case enum.B if var2 in {2, 3, 4, 5}:?

In this case you may use a nested pattern, analogous to the example shown in PEP 636:

  1. match (var1, var2):
  2. case (enum.A, 1) | (enum.B, (2 | 3 | 4 | 5)):
  3. {code block}
  4. ...

(Credits go to RomanPerekhrest's answer, I did not know this before.)

huangapple
  • 本文由 发表于 2023年7月14日 01:34:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定