Structural pattern matching in Python 3.10

I just discovered this, found it quite cool, and thought it might be of interest for others here. Python’s next version, 3.10, introduces structural pattern matching, and uses an IF example for the tutorial:

4 Likes

It’s going to take me a bit of time to reconcile that with what I currently understand to be Pythonic idiom :astonished:

1 Like

Thank you for link. That looks very interesting.

I do have the text, Make Your Own Python Text Adventure by Phillip Johnson, which basically a Python intro using a simple text adventure as a mechanic.

2 Likes

Criticisms like this may be overblown, but there’s definitely a real problem here. Check this example:

NOT_FOUND = 404
match status_code:
    case 200:
        print("OK!")
    case NOT_FOUND:
        print("HTTP Not Found")

This code won’t match against the NOT_FOUND variable, it will actually overwrite the variable with whatever status_code is! Not even just that it would introduce a new variable shadowing the outer one like in other languages, but it would overwrite the existing one! Reading the commentary I know that this is because Python only has function scoping, and changing that would be a far more massive and fundamental change.

This addition to Python may be useful in some situations, but I think I’d worry about the footguns too much to ever actually use it. :frowning:

2 Likes

Funny blog post :smiley:

I’m routinely using Python to parse text in my work, so I’m happy for this, but it’s always good to know about the pitfalls.

1 Like

The Python feature is under active discussion. The PEP634 document is itself a rewrite of PEP622, and there’s counterproposal at PEP642. So what this will look like in final form is not yet decided.

(All links at https://www.python.org/dev/peps/.)

1 Like

Yes. The founding principles of Python were originally that the language was simple and obvious. It was the standard library that gave you all the functionality and power.

I think what’s happened is that as the old guard of core developers are beginning to step back, they need to get some new blood in to replace them. And there has to be something for those new people to do, or else how will they learn?

Hence we are getting some feature creep in what was previously quite a stable language.

Yeah, just think how much better things would be if the old guard hung on forever imposing their views.

(Did you catch the open call for new IFTF board members?)

Anyhow, if you want to push this theory, go look at the authors lists for the pattern-matching proposals and see how long each of these people has been around.

1 Like

Let this just be a lesson that past design choices matter and can constrain what you can do in the future.

2 Likes