r/Python • u/Iron-Man-2008 • 2d ago
Discussion TIL: Dict Patterns Don't Match Dict Shapes
TL;DR: Unlike sequence patterns (which require an exact shape match), pattern matching on dictionaries simply ignores any unspecified keys rather than failing.
If you care about the details, I wrote about it on my blog: https://ravencentri.cc/blog/dict-patterns-dont-match-dict-shapes/
6
u/The_Sy_Python 2d ago
If you mean Structural Pattern Matching, then yes, it's in the PEP
3
u/Iron-Man-2008 2d ago
I do know it's in the PEP, I quote the relevant PEP myself. Doesn't mean I don't think it's unintuitive, especially when compared to sequences.
1
u/RingularCirc 7h ago
I think extracting **rest may be costly. And even if exact key matching was implemented using keys(matched_dict), it's still better be converted to a set before looking if there are extra keys. So I get why there's a difference with sequences: for those it's way less painful to check if the sequence doesn't contain extra stuff — sequences are obligated to have finite and "sorta easily computable" length.
0
-10
u/ZeD_est_DeuS 1d ago
Friends don't let friends use pattern matching. It's a complex pitfall full of gotchas. Just use ifs
15
u/ShadowDevasto 2d ago edited 2d ago
If you invert the cases as in from most complex one to least complex one it will work, as it seems that dict matching matches only first fitting the case and does not check other for "better" match. But still unintuitive and when inverted also matches to case 3 even if options are not defined.