[Python-ideas] Match statement brainstorm

Stephen J. Turnbull stephen at xemacs.org
Fri May 27 03:20:33 EDT 2016


Greg Ewing writes:

 > Trying to come up with some real-looking examples:
 > 
 >     switch obj:
 >        case Point(?x, ?y):
 >           print("Point at", x, y)
 >        case Line(start = ?p1, end = ?p2, width = ?w):
 >           print("Line from", p1, "to", p2, "with width", w)
 >        case Intersection(?obj1, ?obj2):
 >           print("Intersection of", obj1, "and", obj2)

Suppose I want to destructure the Points determining the Lines
determining an Intersection when I print an Intersection, say:

    print("""Intersection of
  Line from ({1},{2}) to ({3},{4}) with width {5} and
  Line from ({6},{7}) to ({8},{9}) with width {10}
""".format(obj.obj1.p1.x, obj.obj1.p1.y,
           obj.obj1.p2.x, obj.obj1.p2.y,
           obj.obj1.w,
           obj.obj2.p1.x, obj.obj2.p1.y,
           obj.obj2.p2.x, obj.obj2.p2.y,
           obj.obj2.w))

What would the full destructuring bind of an Intersection look like?
(I recognize that in your use case, obj1 might be a Circle.  Let's not
worry about that yet, unless it's easy.  I also recognize that most
likely you intended this routine to be called recursively, but let's
assume that isn't so: it is the nested case where I would really like
destructuring.  If it must be done recursively, I wouldn't care if I
had to write code like that below.)

If I can't do that, I won't really get too upset about using

    if isinstance(obj, Point):
        print("Point at", obj.x, obj.y)
    elif isinstance(obj, Line):
        print("Line from", obj.p1, "to", obj.p2, "with width", obj.w)
    elif isinstance(obj, Intersection):
        print("Intersection of", obj.obj1, "and", obj.obj2)

instead of the switch ... case syntax.



More information about the Python-ideas mailing list