|
|
Log in / Subscribe / Register

"Structural pattern matching" for Python, part 2

"Structural pattern matching" for Python, part 2

Posted Sep 8, 2020 7:29 UTC (Tue) by johill (subscriber, #25196)
In reply to: "Structural pattern matching" for Python, part 2 by johill
Parent article: "Structural pattern matching" for Python, part 2

And maybe CapturedVar() can be callable again, returning another CapturedVar() instance with a type attached, so you can write

  from matching import match, capture

  with match(p) as matches:
    if m := matches((capture.x(int), capture.y(int))):
      print("Diagonal at %d" % (m.x, ))
    elif m := matches((0, capture.y(int))):
      print("X-axis at %d" % (m.y, ))
    elif m := matches((capture.x(int), capture.y(int))):
      print("Point at (%d, %d)" % (m.x, m.y))
    elif m := matches((capture.x, capture.y)):
      raise ValueError("It's a tuple, but not with integers")
    else:
      raise ValueError("Not a 2-tuple")
  return Point(*p)


The LWN site is currently under high scraper load, so comment display has been suppressed for anonymous users. If you are a human, you may read the comments by clicking the button below:

Note: you can avoid this step in the future by logging into your LWN account.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds