Ned Batchelder recently shared Real-world match/case, showing a real example of Python’s Structural Pattern Matching. These real-world examples are a great complement to the tutorial, so I’ll share mine.
While working on some STAC + Kerchunk stuff, in this pull request I used the match statement to parse some nested objects:
for k, v in refs.items(): match k.split("/"): case [".zgroup"]: # k = ".zgroup" item.properties["kerchunk:zgroup"] = json.loads(v) case [".zattrs"]: # k = ".zattrs" item.properties["kerchunk:zattrs"] = json.loads(v) case [variable, ".zarray"]: # k = "prcp/.zarray" if u := item.properties["cube:dimensions"].get(variable): u["kerchunk:zarray"] = json.loads(refs[k]) elif u := item.properties["cube:variables"].get(variable): u["kerchunk:zarray"] = json.loads(refs[k]) case [variable, ".zattrs"]: # k = "prcp/.zattrs" if u := item.properties["cube:dimensions"].get(variable): u["kerchunk:zattrs"] = json.loads(refs[k]) elif u := item.properties["cube:variables"].get(variable): u["kerchunk:zattrs"] = json.loads(refs[k]) case [variable, index]: # k = "prcp/0.0.0" if u := item.properties["cube:dimensions"].get(variable): u.setdefault("kerchunk:value", collections.defaultdict(dict)) u["kerchunk:value"][index] = refs[k] elif u := item.properties["cube:variables"].get(variable): u.setdefault("kerchunk:value", collections.defaultdict(dict)) u["kerchunk:value"][index] = refs[k] The for loop is iterating over a set of Kerchunk references, which are essentially the keys for a Zarr group. The keys vary a bit. They could be:
...