Follow Slashdot blog updates by subscribing to our blog RSS feed

 



Forgot your password?
typodupeerror
×
Programming Python

After 19 Years, Python May Finally Get a Pattern Matching Syntax (infoworld.com) 76

"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.
This discussion has been archived. No new comments can be posted.

After 19 Years, Python May Finally Get a Pattern Matching Syntax

Comments Filter:
  • I use match and case extensively in my code base for reasons I refuse to explain. This will devastate my project and I'm mad as hell about it!

    How absolutely dare they create new keywords, it's immoral!

    t. Pythonistas

    • Don't worry - I'm sure when this is implemented it'll be python 4, and that update will break backwards compatibility with python 3 anyway.

    • I understand that you are being sarcastic, but Python is getting a better parser. Because of that and because of the specific syntax being used, new keywords won't have to be created.
  • Wrong indentation (Score:5, Insightful)

    by fph il quozientatore ( 971015 ) on Saturday June 27, 2020 @03:25PM (#60235576)
    The example in TFS has wrong indentation (leading spaces were not preserved). Oh, the irony...
    • That's because Slashdot is written in perl. ;-P

      • The example in TFS has wrong indentation (leading spaces were not preserved). Oh, the irony...

        That's because Slashdot is written in perl. ;-P

        Funny, I get it, but ... It's because the medium here is HTML based, which collapses/ignores extra white space. This wouldn't have been a problem for presenting code in Perl -- or any... other... programming language. [ I may be wrong about that, there may be other messed up programming languages. :-) ]

    • by Osgeld ( 1900440 )

      oh why do people insist on using this horrid "language"

  • by will_die ( 586523 ) on Saturday June 27, 2020 @04:20PM (#60235700) Homepage
    If you are going to add all those different varieties just drop the pain of that and just make it regex.
    Even it the proposal it uses 'similar to', and 'like' regular expressions. Dump all of that and just put in regular expression, and those things that cannot be matched with regex like key-pair, and classes.
    • by bjdevil66 ( 583941 ) on Saturday June 27, 2020 @06:25PM (#60235998)

      I know this is trolling, but based on the ongoing trolling here of PHP and/or Perl, the general consensus on /. is that Python is far superior. How can they post that with a straight face if Python didn't even have an equivalent of strpos() or '$foo =~ /bar/'?

      I mean... What else is missing from Python? print()?

      • switch case
      • Re: (Score:2, Informative)

        by Anonymous Coward

        Perl and Python have explicitly opposing design philosophies [python.org].

        Perl style is to be heavy on operators; Python style is to prefer using words and libraries, so it's a bit more verbose. You write re.search(r'bar', $foo) which is a few more characters than =~ but doesn't involve a built-in operator that does the same thing as a library function---which is considered a bonus in Perl but would be a drawback in Python.

        • Python, especially with version 3, has really strayed away from "There's Only One Way To Do It". This proposal is actually a pretty good example of this, since the whole switch-case thing (or I guess match-case here) is just another way of doing an if-elif-else like you can do with Python today.

          This is particularly annoying with working with other's people's code, as I then get to try to figure out all the clever Python ways they like to do things.

          At least it appears they resisted the temptation of introdu

    • Well, you see, regex was not invented here. So obviously instead of using industry standard regex that's been in use for decades we made up our own vastly superior python-only pattern matching system. Now we can lord it over you troglodytes who won't learn python pattern matching while counting your indents.

    • How does that joke go? Something like..."I had a problem, so I used regex. Now I have two problems."
      https://xkcd.com/1171/ [xkcd.com]

    • Because this is not that kind of pattern matching. Perl has switch [tutorialspoint.com], and regular expressions.

      Note that in the Perl example they're using regex in the case statements. I don't do Python so I'm not sure about this, but it might be flexible enough to put a regex in the proposed statements via a library, making it look like the Perl example.

      The kind of pattern-matching being referred to here is not related to finding patterns in strings, but to selecting execution paths at runtime.

      An if-else ladder is inad

  • For all purposes I wanted "pattern matching" for, using the regular expression module worked just fine. Plus it's compatible with hundreds of other tools and languages using regular expressions. I fail to see how "native" (as in: "language specific") pattern matching could be considered a benefit.
    • by orlanz ( 882574 )

      Second. I didn't like the prior PEPs and don't like this one either. This has always been a gap between Perl and, as you said, I honestly think the re package suffices. Lets not fatten the core language where an optional lib will do. Then those who need it can load it. Its a fairly heavy but well optimized lib.

  • cigarettes have a sin tax.

    • Yep, there is a tax on pattern matching now, but the good news is, as long as you don't think you'll never have to pay.

  • I read through PEP-622 [python.org]. Although it's straightforward if you want to match against literal immutables such as numbers, but it gets tricky if you want to match against variables or classes.

    For example, a little dot in front of a variable name changes the behavior completely:

    case .foo:
    ...
    case foo:
    ...

    And how class matching is supposed to work is not at all clear from the example:

    case Point(x, y):

  • Semantics of | in case 0 | 1 | 2: and case (0 | 1 | 2): is completely different. That’s unfortunate. I wonder why they allow this at all? They could require splitting case 0 | 1 | 2: into three separate lines.
  • by jma05 ( 897351 ) on Monday June 29, 2020 @01:39PM (#60243088)

    If you wished more functional features in Python, but was frustrated by the slow pace of adoption by Python, you can try Coconut.
    It brings Haskell features to Python, sans the strict stuff that does not fit well with a dynamic language. Its great and can be a gateway language to better functional languages.

    It is a super set of Python. So all Python code is valid coconut-lang code.
    It transpiles to pure Python (no coconut dependency), if you need it or can do that by itself.
    There is a Jupyter kernel that works well, which is my main use for it. Functional syntax is great for analytics tasks.

    The only down side is that the error messages need more work, as can be expected from a language with a small dev team.

    P.S: Not a Coconut developer, just a user.

Isn't it interesting that the same people who laugh at science fiction listen to weather forecasts and economists? -- Kelvin Throop III

Working...