This shows how the walrus operator (:=
) can be exploited to write pattern matching without needing PEP622 at all.
Supported patterns:
M._
- wildcard which matches anything(x := M._)
- bound match, result is stored inx.value
M[Class](*args, **kwargs)
- Match an instance of a specific classM([a, *M._, c])
- Match against[a, *_, c]
M([a, *(rest := M._), c])
- Match against[a, *rest, c]
Not implemented but straightforward:
M({a, b, *(rest := M._)})
- Match against{a, b, *rest}
, by addingClassMatcher._known[set]
.M({'a': a, 'b': b, **(rest := M._)})
- Match against{a, b, **rest}
. This would be implemented by makingAny.keys()
returnStarStarMatcher(self)
,Any.__getitem__(self, StarStarMatcher)
returnNone
, and then handlingStarStarMatcher
inClassMatcher._known[dict]
.
Patterns are matched with obj in pattern
:
if obj in M(...):
...
elif obj in M(...):
...
Main differences from PEP 622:
- No special syntax
- Bound values must be accessed with
.value
See examples.py
for some examples.