What is `match` / `case` (structural pattern matching) and is it useful for ops code?
AdvancedConceptLanguage essentials & functions
Answer
Python 3.10's match statement matches shapes, not just values, which is handy for webhook and event payloads:
match event:
case {"action": "opened", "pull_request": {"number": n}}:
handle_pr_opened(n)
case {"detail-type": "EC2 Instance State-change Notification", "detail": {"state": "stopped" as s}}:
notify(s)
case _:
log.debug("ignored event")
It is not a C-style switch: a bare name in a pattern captures rather than compares, so compare constants with dotted names (case Env.PROD:) or guards (case x if x == limit:).
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner