"Structural pattern matching" for Python, part 2
"Structural pattern matching" for Python, part 2
Posted Sep 7, 2020 16:45 UTC (Mon) by ecree (guest, #95790)In reply to: "Structural pattern matching" for Python, part 2 by kleptog
Parent article: "Structural pattern matching" for Python, part 2
On thinking more about this, I have a fairly fundamental question, which I didn't see raised anywhere:
Why can't this be done as a library? Why is a language feature needed?
Something like
import matching
# ...
if m := matching.match(p, (matching.capture('x'), matching.capture('x')):
print("Diagonal at %d" % (m.x,))
elif m := matching.match(p, (0, matching.capture('y')):
print("X-axis as %d" % (m.y,))
elif m := matching.match(p, (matching.capture('x'), matching.capture('y')):
print("Point at (%d,%d)" % (m.x, m.y))
else:
raise ValueError("Not a 2-tuple")
return Point(*p)
Yes, it's more verbose than the 'match' statement, but mainly because of the length of names, and still much more concise and declarative than doing everything with isinstance() and len(). And it makes the difference between constants and capture variables totally explicit!
