Hacker News new | past | comments | ask | show | jobs | submit login
Stack Overflow Users Rejoice as Pattern Matching Is Added to Python (brennan.io)
119 points by srathi on Feb 11, 2021 | hide | past | favorite | 20 comments



The problem that arises here is one of pythons scoping and people reading this satire will have a hard time understanding what is happening (if they don't follow the links in the article).

Taking an example from a reddit comment[1] for the actual pattern matching. The command matched on is a list, and the matching condition in this case is the number of elements in the list.

    command = ['cmd', 'somearg']
    match command:
        case [nonargaction]:
            print(f'We got a non-argument command: {nonargaction}')
        case [action, arg]:
            print(f'We got a command with an arg: {action}, {arg}')
        case _:
            print('default, dunno what to do')
The case gives you named arguments representing the matched strcutre. The scoping problem is, that python will overwrite an existing variable at this scope. Seen here with loops:

    x = 0
    for x in range(5):
        pass
    print(x) # = 4
    m = 5
    match m:
        case x: pass
    print(x) # = 5
Other examples and applications can be found in one of the relevant PEPs 635 [2] (634 is the specification I believe).

[1] https://www.reddit.com/r/programming/comments/lgqhmj/stack_o...

[2] https://www.python.org/dev/peps/pep-0635/


match credulity:

  case woosh:

    print(“We were starting to worry that we would run out of major language changes to confuse new developers. But thanks to pattern matching, we should be set for another 5-7 years! ”)


"I can't wait to start embedding indecipherable state machines in my code using this new pattern matching thing!"


While I initially thought this was absurd, looking at the intended use case I think this is actually sensible behavior. While I would probably use a word other than case to further distinguish it from the switch statements of other languages, the fact remains it's not a switch statement, and assigning values to variables is the whole point.

In the article's example, copied below, the programmer is confident that the status code fits the format they are looking for but not what status code corresponds to not found

    NOT_FOUND = 404
    match status_code:
        case 200:
            print("OK!")
        case NOT_FOUND:
            print("HTTP Not Found") 
This should be handled by an elif statment. If on the other hand we're dealing with

    match ambiguous_response:
        case status_code:
            print("Responded with status code: ",status_code)
        case { "status_code" : status_code , _ }:
            print("Responded with json obj containing status code: ",status_code)
doing so with elif statements would be cumbersome at best.


People seem to read the words "Structural pattern matching" and interpret it as "Pattern matching"... It's a neat little misnamed feature, that's all...


Seriously, who thought such semantics will be useful? What are they smoking?


From what I gather from that article is that pattern matching is the new buzzword for Switch Cases?

If so, expect an influx of applications misusing switches in replacement of if.


It's certainly not, although it can be used in switch cases.

Pattern matching is a great language feature but I've been watching the development of it for Python for a while and have felt nothing but horror.

If you want a great example of how it can be useful and how clear and elegant it can be, check out how it's done in Elixir [0].

There are many other languages that implement it in great ways, I'm sure others will comment on them.

[0] https://elixir-lang.org/getting-started/pattern-matching.htm...


> If you want a great example of how it can be useful and how clear and elegant it can be, check out how it's done in Elixir [0].

If you want to see what it _really_ should look like, see Erlang, and then look at Prolog.


Yes,oddly I love it I Rust, it is probably a favourite feature, but I am not really excited about it in Python.

https://doc.rust-lang.org/book/ch06-02-match.html


Looking at the examples in the doc. That’s just tuple/list unpacking in Python. Am I misreading it?


The linked doc seems to show only what python does as tuple unpacking, but as far as I know elixir can also do the matched unpacking. Based on [1] (which also gives a more matchy example), elixir just has a warning when not using the variable in the case block and you can denote that you want to match against the contents of the variable by prepending ^.

[1] https://www.reddit.com/r/programming/comments/lgqhmj/stack_o...


Yes, just like functions are just a new buzzword for goto.

Structural pattern matching is a lot more than just switch/case, and I while I think pythons implementation looks imperfect, it will still be an amazing boon to the language.

There are a few gotcha-edge cases, but they are of the kind that are obvious once you've encountered them once.

I already know a couple dozen functions in my projects that I'm going to refactor to a fraction of their current length and improve the readability of at the same time as soon as this lands.


Much more than a switch statement. Here's PEP 636, a tutorial: https://www.python.org/dev/peps/pep-0636/


Pattern matching is distinct from switch cases, this is where the "odd" behavior people are taking issue with stems from. If it were a switch case statement, the case behavior would behave differently.


Crikey, that's going to be confusing. Why not separate capture variables from comparison variables by using tuple-style brackets?

  RED = "red"
  colour = "green"
  
  match colour:
    case (RED,):
      print(f"The colour is {RED}")
  
  > The colour is green

  match colour:
    case RED:
      print(f"The colour is {RED}")

  > The colour is red


Pretty funny read


Mapping values to functions was the Pythonic thing for this, right? I guess the solution to that had to be just as unintuitive.


Constants getting overwritten is such a footgun.

Hopefully syntax highlighters and linters will mitigate this.


Actually a pretty good introduction




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: