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.
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.
Re: (Score:1)
Wasn't that supposed to part of the Parrot runtime? :-D
Re: When will it get {} support? (Score:2)
Re: When will it get {} support? (Score:5, Funny)
Why not use python to translate your curly brace python to tabbed python?
Why not just use Perl instead? :-)
Re: (Score:2)
Wonder how many do. Also, steering pedals (Score:2)
I see there are a few existing software projects that do exactly that. I wonder how many people use them. Well, I don't know how many use *Python* to do it, they may use a less toy-like language. ;)
To me, it's like trying to drive a car in which the pedals are for steering and your hands control speed. Theoretically it works fine, but being different from every other car you've ever driven makes it really awkward. Airplanes DO use pedals for the rudder, to go left and right, and a hand-operated throttle,
Re: (Score:3)
I don't find the differences between brace and non-brace languages confusing at all; it's no worse than the fact that every language has different keywords and syntax details.
However, since I learned non-brace languages first (like BASIC, FORTRAN, FORTH, Pascal, PL/I) before I ever used C, I find that the braces just seem to be superfluous and mostly get in the way. It's like trying to drive with a big dog sitting on your lap. (Although at least braces aren't as bad as LISP)))))))))))).
Sure, many languages
Re: (Score:2)
I don't find the differences between brace and non-brace languages confusing at all; it's no worse than the fact that every language has different keywords and syntax details.
However, since I learned non-brace languages first (like BASIC, FORTRAN, FORTH, Pascal, PL/I) before I ever used C, I find that the braces just seem to be superfluous and mostly get in the way. It's like trying to drive with a big dog sitting on your lap. (Although at least braces aren't as bad as LISP)))))))))))). Sure, many languages have closing keywords that are functionally equivalent to braces, but IMO the keywords just look cleaner and they at least remind you which kind of block is being closed.
I agree completely. In fact I've written a bit more about the issue [iki.fi].
It doesn't help that nobody can agree on where to put the braces, and every time you change jobs, you've got to get used to a different formatting standard.
Python has basically the same problem because people may use different depths of indentation, as well as spaces vs. tabs. In fact it's worse, because ugly but correct brace positions will still be parsed correctly, but Python barfs on mixed tab depths.
This is why I think the Fortran/Julia style is the cleanest of all three. Line breaks are significant, so you don't need ugly and redundant semicolons. Indentation is not significant so y
Re: (Score:1)
Re: (Score:2)
Re: (Score:1)
Are you trolling?
Re: (Score:2)
Re: (Score:2)
Re:When will it get {} support? (Score:5, Insightful)
When will they regain there sanity and add support for {} instead of the "space" madness.
Probably about the same time non-Python programmers finally admit this isn't really as huge a problem as everyone likes to pretend.
Re: (Score:2, Insightful)
When will they regain there sanity and add support for {} instead of the "space" madness.
Probably about the same time non-Python programmers finally admit this isn't really as huge a problem as everyone likes to pretend.
So... It's still a problem, just not "as huge a problem"? Great.
There's no significant benefit to white-space block delimiters over (say) braces, but the former has have more potential problems, while the latter has none. Supporting both would be acceptable. The "feature" only exists because the language developer thought/thinks it's elegant, and it is, but it's not inherently better. INB4: The "it looks like pseudo-code" rationalization is weak as pseudo-code almost never translates directly to actual
Re: (Score:3, Insightful)
There's no significant benefit to white-space block delimiters over (say) braces
It forces you to indent your code properly. I've had to read enough code that isn't indented properly that I greatly appreciate Python's forcing it.
Re:When will it get {} support? (Score:4, Informative)
There's no significant benefit to white-space block delimiters over (say) braces
It forces you to indent your code properly. I've had to read enough code that isn't indented properly that I greatly appreciate Python's forcing it.
Good IDEs or editors, like Emacs, can reliably (re)indent code properly -- even entire blocks, functions and files -- with a *single* key-stroke/sequence. This renders your issue into a non-issue, except for languages that rely on the programmer to supply the proper indentation. In those cases, the only fix is manual, which is a bigger problem. (Admitting that, perhaps, editors, like Emacs, can also (re)indent at least some Python code automatically.)
Re: (Score:1)
...good IDEs will handle spaces and tabs for you. So what the hell are you whining about. You just stated the solution to your faux problem. Frankly any programmer that whines about spaces vs {} is this day and age is using inefficient tooling and I wouldn't touch them with a barge pole. We ask opinions on spaces vs {} in interviews, its a great way of filtering out the whiny fuckwits who can't adapt and will cause problems later for the company by tying themselves in knots over trivial bullshit.
Re: (Score:2)
...good IDEs will handle spaces and tabs for you.
If Python code is indented incorrectly, an editor/IDE can't (always) re-indent it correctly as it can't read the mind of the coder. This isn't a problem with brace (non-whitespace) block delimiters. Probably not a problem unless the code gets borked, then the only fix is manual. (P.S. Your generic name-calling attitude is immature.)
Re: (Score:2)
If Python code is indented incorrectly, an IDE can't re-indent it correctly
The same is true for when {} are not curled correctly. But wait, can you make an IDE to show imaginary curly braces in your Python code? Does that make your problem go away? You are welcome!
Re: (Score:3)
As I said lower down. Indentation and braces are just to different ways of representing exactly the same logic. Any criticism you apply to whitespace in terms of the computer parsing the code applies equally to braces and vice-versa. The difference is the human layer, the presentation. The only valid complaint is "I don't like typing spaces", but then you'd be a poor team C/C++ etc... coder too. The braces add NOTHING if you already cleanly indent code as the intent can be entirely inferred from the indenta
Re: (Score:3)
Missing a brace can't be solved by your IDE any better than missing whitespace. There is no behavioural difference as far as the parser is concerned between " CODE\nCODE" and "{CODE}CODE", it is just a different delimitation scheme. You could write a short segment of code to convert one into the other.
Once you drill down into the topic you find that the real reason people don't like using spaces or tabs is simply because they get burned using an editor without auto indentation and think using spaces is t
Re: (Score:2)
Anyone incapable or resistant to using modern IDE doesn't get hired...
I'm not sure whether it counts as a modern IDE, but Spyder drives me crazy with all the "helpful" popups (on function arguments) that obscure my own code and grab the enter key so that I get "ArithmeticError" inserted or not depending on how many milliseconds I wait before I press Enter at the end of a line.
I prefer emacs (without autocomplete other than M-/ ). A bit more time in looking up function arguments is made up for by things like more efficient keyboard use and easily having multiple files (or the
Re: (Score:1)
Missing a brace can't be solved by your IDE any better than missing whitespace.
No, but when you type a closing brace or parenthese, and emacs says "What the HELL is that for?!?"**, it kind of indicates you have a problem.
**stock error messages are for wimps.
Re: (Score:2)
A problem that literally doesn't exist with indentation delimiting as there are no braces...! Spend a few minutes and think it through properly.
Assume a developer is using good practice and indenting code to show scope for readability
* indentation is now performing exactly the same purpose as the braces, there is redundant information
* braces don't add to readability relative to indentation, so why have the braces at all
* there is no difference to a compiler/interpreter parser front end of using braces or i
Re: (Score:1)
I'm glad you ask a question like that during an interview... it would warn me that you're bunch of intolerant egomaniacal twits that I really, really, really wouldn't want to work for.
Re: (Score:2)
It is a surprisingly good question to be able to determine someone's reasoning skills when expanded. It provides a good discussion for teasing out ecosystem knowledge, working with others, their understanding of how humans parse information and fundamental understanding of information and redundancy.
Re:When will it get {} support? (Score:4, Insightful)
All I'm saying is that when I did some actual Python programming in a production environment a few years back on a contract job, the "issue" with whitespace never came up. Not once. Because, you know, I just sort of watched out for it. That's literally all it took. As a pragmatist, I'll acknowledge something is a potential issue if I see it. But as far as I can tell, it's a *very* minor *potential* issue. I had a lot more issues with its implicit conversions doing things with variables I didn't expect - like, actual bugs that got hidden, and which had a side effect of just making my code silently not work for mysterious reasons. That's one reason people say Python isn't best suited for large-scale development, and I agree with that.
But really, what Holy Writ language are you working on that DOESN'T have some serious flaws? Hell, my normal job is working in C++. You want to talk about flawed languages? And yet, somehow, I get work done in it, because it has a lot of strengths as well as flaws. All languages are like that. I mean, except Rust, of course. Every Rust programmer knows Rust is perfect. And the rest of us heathens will learn someday.
Perhaps the C++ equivalent is C programmers complaining about how C++ might do all sorts of insane things under the hood hidden in an operator overload, or something like that. Do you want to know how many times in two decades of C++ work I've seen that specific overloaded operator thing as an actual problem? Yep. Zero. Because overloading the operator like that would be stupid. As such, most people don't do it. And if they do, you smack them on the head in a code review and say "don't be stupid." It's a complete straw-man issues that sounds like it could be bad, but never really comes up in practice. I'm convinced Python whitespace is like that as well.
Re: (Score:1)
Sure, I get that, but if the indentation gets borked then the code is functionally borked, the only fix is (mostly) manual. In Perl (and other languages, like C), it's a single key-sequence in Emacs to correctly auto re-indent the entire file -- and indentation doesn't even matter from a functional standpoint. Using white-space for block delimiters in Python is an unnecessary point of potential problems that could have easily been fixed by using braces in the languages. That's all I'm sayin'.
Re: (Score:2)
it's a single key-sequence in Emacs to correctly auto re-indent the entire file
Write an Emacs macro to show ephemeral curly braces for your viewing pleasure. Once that works you don't need to C-M-\ ever again. Not saying this macro is needed but it sounds like it will make you whole again.
Re: (Score:2)
Worst 30 seconds of my day.
Re: (Score:1)
When will they regain there sanity and add support for {} instead of the "space" madness.
Probably about the same time non-Python programmers finally admit this isn't really as huge a problem as everyone likes to pretend.
As Slashdot has just demonstrated, it is a real problem when displaying your program or, worse, printing it out makes it ambiguous.
A language that has laboured under a fundamentally stupid design mistake for 3 major versions does not deserve to be taken as seriously as it's fans like to pretend.
The Python whitespace thing has no upside and at least some downside; it should be scraped.
Re: (Score:2)
"Probably about the same time non-Python programmers finally admit this isn't really as huge a problem as everyone likes to pretend."
Your assertion that it's not a big problem would be more convincing if the summary hadn't banged its head on it.
Re: (Score:2)
Probably about the same time non-Python programmers finally admit this isn't really as huge a problem as everyone likes to pretend.
You've never used Python in a team where one or more people haven't realized they're using tabs instead of spaces.
Nor have you ever tried to debug Python where a simple "if(foo == something){ buncha if'd out code)} would be useful.
I love Python. It's biggest problem is using spaces to specify blocks of code.
Re: (Score:2)
You know that code isn't pythonic right? That "{buncha if'd out code)}" is not proper python. If that is more than a short line of code, it should be a block or a function call. You can do "if foo==something: stmt1; stmt2". But doing more than 3 short statements kind of falls out of being pythonic. it all comes down to legibility.
Re: (Score:2)
I assume the poster is referring to there not being a really good way to quickly comment out blocks of Python code for debugging purposes. You have the triple quotes, but like /* ... */ for C, it doesn't handle nesting comment blocks, and you can't just throw in a #if 0 ... #endif. I've done a "if False:", but that then requires me to indent the block of code under the if statement which is annoying.
Of course, that was more a problem I had a decade ago. Today most any decent editor today has some way of
Re: (Score:1)
Space madness is unfortunately widespread. As every real programmer knows, the only proper way to indent lines is with tabs.
Fortunately we built this nice ark over here to take all you " " and "{}" heathens, er, kind souls to a better world. Just hop aboard. The rest of us will be right behind you...
Re: (Score:3)
Python has had support for {} since its inception. Here is an example:
if x > 3:
#{
print("x is greater than 3!")
#}
Just Fucking Great (Score:1)
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
Re: (Score:2)
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.
Re: (Score:2)
Wrong indentation (Score:5, Insightful)
Re: (Score:3)
That's because Slashdot is written in perl. ;-P
Re: (Score:2)
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. :-) ]
Re: (Score:2)
Makefiles can be dangerous on the web. Seems to be a programming language.
Re: (Score:3)
Re: (Score:2)
Re: (Score:1)
oh why do people insist on using this horrid "language"
Re: (Score:3)
Because it requires a trivial amount of effort to produce a good enough solution to most problems.
Re: Wrong indentation (Score:1)
That's what Perl was for. Why was python made after that?
Re: (Score:1)
Re: (Score:2)
So that someone else can understand it ^_^.
Perl = fastest brain dump [individual brains think differently]
Python = one obvious way most agree on
Re: Wrong indentation (Score:1)
Perl just works. It's just dumbed down C without pointers but with native regex and a huge add one library. If someone has trouble with regex in Perl they'll have the same trouble with regex in anything else.
Re: (Score:2)
Perl just works. It's just dumbed down C without pointers but with native regex and a huge add one library. If someone has trouble with regex in Perl they'll have the same trouble with regex in anything else.
If your problem involves regex in its solution, you now have two problems.
Re: (Score:1)
Right. Because 37 individual case statements are much better.
All of those varieties and no regex? (Score:4, Insightful)
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.
Python has no pattern matching regex? Huh... (Score:4, Insightful)
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()?
Re: (Score:2)
Re: (Score:2, Informative)
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.
Re: (Score:2)
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
Re: All of those varieties and no regex? (Score:1)
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.
Re: (Score:2)
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]
Re: (Score:2)
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
I'm fine with "import re" (Score:2)
Re: (Score:2)
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.
In my state, (Score:2)
cigarettes have a sin tax.
Re: (Score:2)
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.
How does it work with names/classes? (Score:2)
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:
And how class matching is supposed to work is not at all clear from the example:
or (Score:1)
Coconut lang (Score:3)
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.
Re: (Score:2)
Forgot to add the links.
http://coconut-lang.org/ [coconut-lang.org]
https://coconut.readthedocs.io... [readthedocs.io]