“A proposal under consideration by Python’s development team would finally bring pattern matching statements to the language,” reports InfoWorld:

The creators of the Python language are mulling a new proposal, PEP 622, that would finally bring a pattern matching statement syntax to Python. The new pattern matching statements would give Python programmers more expressive ways of handling structured data, without having to resort to workarounds…

While Python has lacked a native syntax for pattern matching, it has been possible to emulate it with if/elif/else chains or a dictionary lookup. PEP 622 proposes a method for matching an expression against a number of kinds of patterns using a match/case syntax:
match something:

case 0 | 1 | 2:
print(“Small number”)
case [] | [_]:
print(“A short sequence”)
case str() | bytes():
print(“Something string-like”)
case _:
print(“Something else”)

Supported pattern match types include literals, names, constant values, sequences, a mapping (basically, the presence of a key-value pair in the expression), a class, a mixture of the above, or any of those plus conditional expressions. Any matches that are ambiguous or impossible to resolve will throw an exception at runtime…

If an object implements the __match__ method, it can be used to test if it matches a given class pattern and return an appropriate response.

One of the authors of the new PEP was Python creator Guido van Rossum, according to the article — and he’d drafted an earlier pattern matching proposal back in 2006 that was rejected (following the rejection of an earlier proposal in 2001).

The article also notes that many aspects of this PEP were inspired by the way pattern matching works in Rust and Scala.

of this story at Slashdot.

…read more

Source:: Slashdot