Approved to add operators for pattern matching in Python

The Python Project Governing Body approved to be added to the language operators for matches with pattern (match and case). Support for new operators will appear in the Python 3.10 release. The new “match” and “case” operators will improve the readability of your code, make it easier to match arbitrary Python objects, and debugging, and also improve the reliability of the code thanks to the possibility of extended static type checking.

The implementation is much like the “match” operator provided in Scala, Rust, and F #, which compares the result of a specified expression against a list of patterns listed in blocks based on a “case” statement. Unlike the “switch” operator available in C, Java, and JavaScript, match expressions offer much more broad functionality .

def http_error (status): match status: case 400: return “Bad request” case 401 | 403 | 404: return “Not allowed” case 418: return “I’m a teapot “case _: return” Something else “

For example, it is possible to unpack objects, tuples, lists and arbitrary sequences to bind variables based on existing values. It is allowed to define nested templates, use additional “if” conditions in a template, use masks (“[x, y, * rest]”), map key / value bindings (for example, {“bandwidth”: b, “latency”: l} to extract “bandwidth” and “latency” and dictionary values), extract subpatterns (operator “: =”), use named constants in a template. In classes, you can customize the matching behavior using the “__match __ ()” method.

from dataclasses import dataclass @dataclass class Point: x: int y: int def whereis (point): match point: case Point (0, 0 ): print (“Origin”) case Point (0, y): print (f “Y = {y}”) case Point (x, 0): print (f “X = {x}”) case Point () : print (“Somewhere else”) case _: print (“Not a point”) match point: case Point (x, y) if x == y: print (f “Y = X at {x}”) case Point (x, y): print (f “Not on the diagonal”) RED, GREEN, BLUE = 0, 1, 2 match color: case .RED: print (“I see red!”) case .GREEN: print (” Grass is green “) case .BLUE: print (” I’m feeling the blues 🙁 “)

Previously, attempts to implement pattern matching operators were made in 2001 and 2006 ( pep-0275 , pep- 3103 ), but were rejected in favor of optimizing the “if … elif … else” construct to construct matching chains. there was no division of opinions and for the final decision-making, the governing board was involved as an arbiter, which managed to come to a consensus.

/Media reports.