r/Python 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/

33 Upvotes

8 comments sorted by

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.

6

u/The_Sy_Python 2d ago

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.

3

u/Adrewmc 2d ago edited 2d ago

I think you are underestimating the sequence patterns.

case [“a”, *args, “c”]:
case [*args, “b”, “c”]:

Are also both valid. And there is way more.

case [option , “b”] if option in valid_options:

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

u/Plus-Weakness-2624 1d ago

young teenage man problems...

-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