"Structural pattern matching" for Python, part 2
"Structural pattern matching" for Python, part 2
Posted Sep 8, 2020 23:39 UTC (Tue) by ecree (guest, #95790)In reply to: "Structural pattern matching" for Python, part 2 by johill
Parent article: "Structural pattern matching" for Python, part 2
because you quite probably cannot instantiate a Point() object with two CapturedVar instances.
But can't you, though?
As long as CapturedVar suitably 'ducks' its type (e.g. for ints, implementing + and **, like you suggested), Point.__init__ should be entirely happy with it unless it's trying to do things that depend on the actual values.
Sure, it's not something that will work for every class, but nor is the rest of the "Match Protocol" in PEP 622. And if the class has a __match_args__, then you could potentially have a matching.Duck that uses that to "play the rôle of" the class in a match expression:
from matching import match, capture, Duck
with match(p) as matches:
if m := matches(Duck(Point)(capture.x(int), capture.x(int))):
print("Diagonal at %d" % (m.x, ))
elif m := matches(capture.p(Point)(capture.x(int), capture.y(int))):
# the second call on capture.p implies a Duck
# if the match succeeds, it is replaced with the concrete Point
print("Other point at %s % (m.p, ))
So you'd use plain Point() for dataclasses and anything else that's not too fussy, Duck(Point)() otherwise.
Still not quite as pretty as the PEP 622 syntax, but it still seems like a good way to get experience with "how this feature would be used in practice" before baking it into the language. Which to my mind is reason enough to do it.
