88 points · by Sami_Lehtinen · 5y ago · 121 comments
Well, yes, but actually, no.
A switch operator, at least in most other languages, uses comparison to select a branch. Only comparisons are performed (either with each branch or optimized for direct access) but no other side effect. Pattern matching, as with other languages too, tries to 'match' the variable to the pattern. If it succeeds, then the branch is taken and the variables (if any) are assigned, which in python means that they are assigned to the whole current function. This is a big side effect.
And that's the main problem, the variable constants. Once you understand the issue it is relatively easy to fix, but for a newcomer this will probably be a few minutes of searching and debugging.
Python don't have a switch statement, at least not yet, pattern matching is just another similar feature that can be adapted to work similarly, like the chain of elifs and the lambdas dictionary. However if you want to say otherwise...at least give the warning of the constants at the beginning, not at the end.
Assignment is not generally a side effect, and even if it were, matched branches in a switch statement potentially having side effects or externally visible variable (re)assignments is normal in languages with switch. (Ironically, match-based assignments visible outside the pattern match expression aren’t typical in languages with pattern matching, so actually the behavior you describe is more typical of switch statements than pattern matching, which is typically a block-scoped expression with local bindings.)
However, there are some special cases where variable scope is smaller than a whole function, e.g. within list comprehensions.
Or we can think of a list comprehension as a function doing a loop/collect under the scenes.
I don't really understand the logic behind this comment. You're pointing this out like it's some contradiction in people's opinion.
But it's not like "block scope" is the one and only determinant of whether a language is good or bad, so lack of that alone would negate the above statement.
js could be bad and python good, regardless of whether Python lacks block scope. Doubly so since js also lacks it by default, and has only sort of tacked-it on with let/const.
But the even better answer is that both are languages with different strenghts and tradeoffs, that JS did have several bad design decisions early on, that both have evolved, and x=bad, y=good is a fanboi reaction, not a developer reaction.
1) it's "opt in" (you need to explicit implement the dunder method) and
2) it's only for specific classes, you cannot change the behavior of 1 == "one"
More clearly because builtins are protected from monkey-patching, you can’t change the behavior of == where both operands are builtins. “Only for specific classes” implies the scope of applicability is much narrower than it is.
Namely matching an item in a dictionary based on either key or perhaps more advanced matching a value inside the dict. Maybe even using re to match it.
Either way, I find using a dictionary is the most Pythonic and clean way to do it. Defining the actions first, how to match them and anything else they might need.
> _Statement vs. Expression._ Some suggestions centered around the idea of making `match` an expression rather than a statement. However, this would fit poorly with Python's statement-oriented nature and lead to unusually long and complex expressions and the need to invent new syntactic constructs or break well established syntactic rules. An obvious consequence of match as an expression would be that case clauses could no longer have arbitrary blocks of code attached, but only a single expression. Overall, the strong limitations could in no way offset the slight simplification in some special use cases.
To give a concrete reason: Python's significant whitespace makes nested expressions much trickier to write/parse
I know which one I would bet my money on.
Entirely seriously, what are the trade-offs? I've heard general defences of it, for example nchammas's quote from van Rossum in a sister post to yours, but they all seem quite general—"it'll complicate things", but in a way that seems only to boil down to "it's unfamiliar and I don't like it." Which, to be fair, is van Rossum's prerogative to say—but it doesn't seem persuasive in light of general language design.
There are many situations where you want lots of branching because that's the problem domain, and trying to hide the essential aspect of the problem domain isn't helpful for code readability or maintainability.
If you are writing an interpreter, case statements are a natural thing. Yes, you can write that intepreter with expressions that are statements in disguise, but just because something can be done doesn't mean that it should be done. An interpreter is just a dispatcher waiting for some trigger from the outside and then firing off a command handler depending on the trigger. Just like a UI. GUIs are are also natural things to write with event driven patterns. If user clicks on box A, then do X, if User clicks on box B, do Y. That is a big case statement in disguise except the underlying framework handles that for you and you just write the code for X and Y. But if you didn't have that UI toolkit doing heavy lifting you would find yourself writing event loops and case statements to implement it as the most natural (non-ideological) solution.
Similarly, there are many situations where you want to handle exceptional conditions separately in a clear way that allows you to easily understand what the exceptional logic is and change it without touching the main processing flow at all. It all depends on the problem domain. Or the problem domain may require feedback where the handler tells the dispatcher to change the dispatch algorithm.
On the other hand, fluent APIs work well with streams of data that are processed sequentially. There the natural approach is to apply a sequence of functions to the stream. You want to avoid lots of nesting of case statements as the code would be ugly.
It boils down to minimizing complexity. You could write that event driven dispatcher as a function that takes as its inputs all the possible callbacks and the state of the world and spits out a specific callback. But that would be a more complex program that is harder to read and write, and thus is more error prone, regardless of the fact that in theory it is easier to refactor and unit test by dropping in a different function. In practice, it is not easier, it is harder. So when someone like Guido says, "it will complicate things", no it doesn't boil down to "I'm unfamiliar and don't like it", what it means is "I've spent a couple of decades writing code, have been up and down this road more times than you have, and I know it's a harder road to travel".
No, as it's just an ideology, and not some absolute engineering truth.
The philosophy of python is there should be only one pythonic way of doing things.
But more and more features are being added that give too many options with minor benefit
How is case different from the elif pattern? What does the walrus operator do that we really need.
Each one of these things on their own if fine but I'm worried together it's going to make python increasingly idiosyncratic to each developer and, consequently, harder to read.
Python's Zen beat out perl's TMTOWTDI. But python seems to try to be more and more like perl with every release: more appealing to hackers playing code golf than long term readers of the code base
Pattern matching is often conflated with switch-case by people who are unfamiliar, because pattern matching subsumes switch-case, but they're very much not the same thing. Structural pattern matching is much more powerful than checking a series of boolean conditions. It allows you to not only check the structure of a value, but bind parts of that structure to variables. It allows you to express logic that would would otherwise be fairly complex in a straightforward and transparent way.
> If the implementation is easy to explain, it may be a good idea.
Pattern matching is extremely complex, and for what?
for foo, (bar, baz) in nested_tuple_list:
...
This works as expected. The current 3.10 implementation is just half-baked. They should have expanded the existing pattern matching facilities (added support for data structure destructuring).Presumably then you could just have used the existing walrus operator inside the already existing if-else constructs.
That would have been the obvious path of least surprise. What we got instead seems inadequate.
Pattern matching is not (necessarily) extremely complex as it exists in a multitude of languages these days. Powerful does not automatically imply complex.
The philosophy of anything (python, unix, etc) is usually just cargo cult early bogus idealism.
What happens later is that reality and pragmatism come into play.
People don't want simple languages, people want more features.
I think it’s a mistake to defer to the zen of python without considering the PEPs themselves which do discuss trade offs. (I’ll note that you didn’t make that claim but GP did).
Was it tho? It's one of my favorite improvements, and has no actual downside.
- It violates the longstanding Python rule that assignments don't escape the enclosing scope.
I get it, languages have to grow or fix mistakes. I read about Python long before I attempted to program in it and even I (not a language designer or that special) knew that their handling of division as being integer division as a default was a long-term problem that would eventually be changed one way or another. And so it was.
I absolutely agree on the walrus operator. It's too terse and while on its own it only makes two steps into one, it's not used alone, making each line of code with it that much harder to unpack.
I don't know enough about pattern matching but my feeling is that we got along without it so far ...
That ship has sailed more than a decade ago.
(And if we're on a crusade to make Python pythonic again, let's start with the bigger fish - like the sync/async function distinction. Somehow Python managed to fall into the red/blue function trap the hardest.)
What should have been done here?
Thiiis really hasn't been my experience with the Python community. Every place I've worked on a Python codebase has done it a different way, and none of them have agreed on what is "pythonic".
Each team has claimed that _their_ approach is the most python-y way to do it, but they've all celebrated Python as not being "restrictive" like "other" languages. It's really weird.
Exactly my experience from day one. It's a laughable statement that the Python community keeps repeated with almost no basis in reality.
With all due respect to your (otherwise perfectly valid) argument, "there's more than one way to do it" was never a real problem with people using Perl. I dare say it's fully possible to write difficult-to-read code in any language.
Perl was expressly never interested in erecting glass walls and force people this or that way. Not saying that this is good or bad. But it's the way the people who are making Perl want it.
Maybe people got into python when Google took it for a serious use just like people got into git because of Linus but figured it wasn't the best tool a decade later but the ecosystem is already there it is too late to swap.
The Zen is against alternatives for the sake of alternatives, but not for facilities focussed on different use cases. Though as the use cases get more finely divided, the difference is less peeceptible.
1.a lot of 'if'-statement 2.using a dict and the value is a function you call if the key matches
Or what else?
That sounds like a desperate plea to get stuck with a bug-riddled unmaintainable mess of a module.
If all you want to do is pick one of a finite set of possible code paths, it is never a good idea to generate a hash to pick from a map/array.
Even chained if/else if statements are cleaner than that mess.
Now, every two releases they add a "language feature". Some library maintainers jump in the bandwagon, and WOOSH! : half the ecosystem depends on CPython to run. Bye Jython, Cython, PyPy, Micropython, etc and bye the code analysis and code transformation tools : all outdated until more funds or voluntary dev are willing to fix them
In an ideal world, the community should fork Python 2.7, rename it and add type hints. But that's too late, all the dev time was spent on making libraries compatible only with some recent versions of CPython
https://mobile.twitter.com/vasudevram/status/132736428179752...
Anyway, sick of arguing about such meta points. That is not what I come to HN for. I come for intelligent discourse via which I can learn from others' experience and share mine.
I'll just end by saying that I made specific points in that Twitter thread, such as BDD and RDD influencing the language's direction undesirably. To me, that is specific enough a complaint. A language is much more than just a bag of features. YMMV.
bob match {
case Person("bob", _) => println("hi bob!")
case _ => println("I don't know you")
}I think its important that match returns something so you can use outside of a function which this doesn't do.
val greeting = bob match { ... }
I thought it would be a fun exercise to write case classes in python, kind of like an improved immutable data class with a match that returns.
https://mleverything.substack.com/p/scalas-case-class-in-pyt...
as they are positional-only - and you also need to specify all the other placeholders, makes reading the match very difficult
case x:Bar if x.foo = ... =>
?Not true - for example, Black had been requiring python 3.6+ even before 3.5 and older were fully deprecated / unsupported.
Just declare the minimum version your library requires in setup.py and let users decide.
What is meant to be the benefit of not explicitly writing down types in python?
I have used C, C++, GL, and C# most of my career, but recently I have been helping a friend of mine who is learning to code with her python assignments. Things still have types when the code runs, and type errors can cause all sorts of bugs and problems, but the types are not actually written down by you in the code so u have to remember them all. It just seems to add so much more mental load on the programmer + potential for weird hard to find bugs not being caught by compiler and slipping under the radar. It seems objectively worse to me. But I assume there is supposed to be some benefit. What is it supposed to be?
PS Bonus comment: whitespace controlling the flow of the program? Lets make characters that are invisible really important to how the program runs. Thats just plain dumb, that could only be the result of a weird fetish of the originator of the language.
What actually happens is that the variable REGION_EU will now contain the string "NA" and the case will match!
Isn't this the kind of unintuitive behavior that php got criticized for all this time?Of course, I've also used switch statements in do { .. } while (false), so maybe I just need to be voted off the island.
Fall-through can be a useful behaviour, but it's definitely a foot-gun.
Simulating the C switch statement in Python:
https://jugad2.blogspot.com/2016/12/simulating-c-switch-stat...