CKTIS / Python
Schlüsselwort case
Wählt einen match-Zweig durch Muster und danach optionale Schutzbedingung.
Version: Python 3.14; repository image, production runtime not attested
Syntax
case {"qty": q} if q > 0:
...Wählt einen match-Zweig durch Muster und danach optionale Schutzbedingung.
Gebundene Namen stehen in dieser Bedingung bereit. Eine falsche Bedingung lässt weitere Fälle zu. Ein bloßer Name bindet einen Wert, _ ist ein Platzhalter und das Mapping-Muster erlaubt zusätzliche Schlüssel.
Ein unwiderlegbares Muster ohne Guard wie case _: ist nur im letzten Zweig zulässig.
Beispiele
def label(row):
match row:
case {"qty": q} if q > 0:
return f"positive:{q}"
case {"qty": 0}:
return "zero"
case _:
return "other"
print([label(row) for row in ({"qty": 2, "tag": "A"}, {"qty": 0}, {})])
try:
compile("match 1:\n case _: pass\n case 1: pass", "<example>", "exec")
except SyntaxError:
print("unreachable case")
Ergebnis
['positive:2', 'zero', 'other'] unreachable case
Ein unwiderlegbares Muster ohne Guard wie `case _:` ist nur im letzten Zweig zulässig.