Python 3.10 was released on 4 October 2021. The main new feature is structural pattern matching, the match statement (PEP 634, with a tutorial in PEP 636). (What’s New in Python 3.10)
The tutorials I saw show match on simple values, which looks like a switch from other languages. I think that is the least interesting use. It is more useful when you match on the shape of data. I have one script that receives MQTT messages from many devices and has a long if/elif chain on the topic. I rewrote it to see if match helps.
Raspberry Pi OS ships an older Python, so I tried this on my laptop with 3.10. The script will stay on the old version on the Pi until the OS has 3.10.
The old code
Topics look like home/<room>/<device>/<metric> and a few special ones:
def handle(topic: str, payload: dict):
parts = topic.split("/")
if len(parts) == 4 and parts[0] == "home" and parts[3] in ("temperature", "humidity"):
store(parts[1], parts[2], parts[3], payload["value"])
elif len(parts) == 4 and parts[0] == "home" and parts[3] == "status":
set_status(parts[2], payload.get("state"))
elif len(parts) == 2 and parts[0] == "cmd":
run_command(parts[1], payload)
else:
log.warning("unknown topic %s", topic)
It works, but the index numbers make it hard to read, and the length checks are easy to forget.
With match
def handle(topic: str, payload: dict):
match topic.split("/"):
case ["home", room, device, ("temperature" | "humidity") as metric]:
store(room, device, metric, payload["value"])
case ["home", _, device, "status"]:
set_status(device, payload.get("state"))
case ["cmd", name]:
run_command(name, payload)
case _:
log.warning("unknown topic %s", topic)
A list pattern checks the length and the fixed parts at the same time, and binds the variable parts to names. _ matches anything and binds nothing. | means “or”, and as gives the matched value a name.
You can match the payload too. Mapping patterns match dicts and ignore extra keys:
match payload:
case {"value": float(v) | int(v)}:
...
case {"error": str(msg)}:
log.error("device error: %s", msg)
case _:
log.warning("bad payload %r", payload)
float(v) is a class pattern: it checks isinstance(value, float) and binds it to v. This replaced a few lines of isinstance checks and KeyError handling. Note that float(v) does not convert. A string "21.5" does not match.
The traps
A bare name always matches. This is the big one:
STATUS = "status"
match parts[3]:
case STATUS: # does NOT compare with "status"
...
case STATUS: is a capture pattern. It matches anything and assigns the value to a new variable STATUS. Python 3.10 refuses to compile this if more cases follow it (“name capture makes remaining patterns unreachable”), which helps. But if it is the last case, it compiles and silently matches everything. To compare with a constant, use a dotted name, like Metric.STATUS from an Enum or config.STATUS. Dotted names are value patterns.
Order matters. The first matching case wins. Put specific cases before general ones.
Guards for conditions. A pattern cannot express “value > 100”. Use if after the pattern:
case ["home", room, _, "temperature"] if room in IGNORED_ROOMS:
return
Strings are not sequences here. A sequence pattern does not match a str, even though a string is a sequence in Python. I think this is the right decision, but it is different from the rest of the language.
When I would not use it
For a simple mapping from a value to a function, a dict is still shorter and can be changed at runtime:
HANDLERS = {"temperature": store_temp, "humidity": store_hum}
HANDLERS.get(metric, unknown)(payload)
And a library that must run on 3.9 or older cannot use match at all. It is a syntax error there, not just a missing function, so you cannot put it behind a version check in the same file.
For my MQTT router, the match version is easier to read. I will move it when the Pi has 3.10, and not before.