654 points · by eplanit · 5y ago · 518 comments
Direct links to the PEPs themselves, to perhaps save others a little time. Although the LWN write up linked in TFA is a very nice introduction to the topic and its big discussion in the community.
Accepted:
Specification https://www.python.org/dev/peps/pep-0634/
Motivation and Rationale https://www.python.org/dev/peps/pep-0635/
Tutorial https://www.python.org/dev/peps/pep-0636/
Rejected:
Unused variable syntax https://www.python.org/dev/peps/pep-0640/
Explicit Pattern Syntax for Structural Pattern Matching https://www.python.org/dev/peps/pep-0642/
"I dislike the syntax and semantics expressed in PEP 634. I see the match statement as a DSL contrived to look like Python, and to be used inside of Python, but with very different semantics. When you enter a PEP 634 match statement, the rules of the language change completely, and code that looks like existing Python code does something surprisingly very different. It also adds unprecedented new rules to Python, e.g. you can replace one expression with another in the exact same spot in your code, and if one has dots and the other doesn’t, the semantics of what the statement expresses changes completely. And it changes to yet a third set of semantics if you replace the expression with a single _.
I think the bar for adding new syntax to Python at this point in its life should be set very high. The language is already conceptually pretty large, and every new feature means new concepts one must learn if one is to read an arbitrary blob of someone else’s Python code. The bigger the new syntax, the higher the bar should become, and so the bigger payoff the new syntax has to provide. To me, pattern matching doesn’t seem like it’s anywhere near big enough a win to be worth its enormous new conceptual load."
This while we have elephants in the room such as packaging. Researching best practices to move away from setup.py right now takes you down a rabbit hole of (excellent) blog posts, and yet you still need a setup.py shim to use editable installs, because the new model simply doesn't yet support this fundamental feature.
I can't afford to spend days immersing myself in packaging to the point of writing a PEP, but would help pay someone to do it well. I can see no way to fund packaging efforts directly on the PSF donations page (edit: see comment). It's great to see Pip improving but there is still not even a coherent guide that I can find for packaging using up-to-date best practices. This appears to be because the best practices are currently slightly broken.
[0] https://discuss.python.org/t/gauging-sentiment-on-pattern-ma...
There is a part of me that wonders, at this point, if basically every new addition to the language itself is secretly just a medium for procrastinating on figuring out what to do about setup.py.
I'm not as down on this PEP as some other seem to be, mind. It's just that, when I think about my actual pain points with python, this language addition starts to look like a very, very fancy bike shed.
But I admit I use setupmeta for auto definition of the version, and it just makes setup.py even better, but that's basically the only thing I like to add to setup.py, because it simplifies package publishing scripts. I haven't found any feature in pip to verify the gpg signatures that it allows us to upload packages with (python setup.py sdist upload --sign).
As for pattern matching is not specific to Python, it's available in many other languages and is a joy to use in OCaml, I see no reason why Python would not have pattern matching.
The thing is this: You can add something which, in isolation, seems desirable and positive -- but in the greater picture, is a net negative due to the complexity it adds.
People might say that those who do not like the pattern matching syntax are not obliged to use it. But when developing code in longer-running projects, far more code is read than written. Adding syntax, especially with complex edge cases, especially from languages which use concepts that are at the core quite alien to Pythons main concepts, adds a burden which is difficult to justify.
One thing that Larry Hastings refers to seems often to be underestimated - readability.
It seems nice to be able to do code golfing and use pattern matching to reduce an expression from maybe 50 lines to 10.
But what matters far more is that one can read code easily, without guessing, and without consulting definitions of edge cases. Even in smaller projects, one will read 10 times more code than one writes. In larger projects and as a senior programmer, that could be a factor 100 or 1000. Not that unusual to work one week through a bug in someone else's code, and fix it by changing a single line. As code becomes more complex, it becomes really important to understand exactly what it means, without guessing. This is key for writing robust, reliable and correct code (and this is perhaps why the ML and functional languages, which stress correctness, tend to be quite compact).
And while it might be satisfying puzzle-solving for smart and easily bored people, like you and me, to write that pattern matching code and reduce its length, it is just not feasible to read through all the PEPs describing surprising syntactic edge cases in a larger code base.
Meanwhile, Julia supports pattern matching due to macros: https://github.com/kmsquire/Match.jl
https://github.com/thautwarm/MLStyle.jl
https://thautwarm.github.io/MLStyle.jl/latest/syntax/pattern...
Coming back to that, just a reminder that lambdas in Python are still gimped, closures do not work as expected because of -- scoping, and core developers in Python 3 tried to remove with "map" and "filter" tools that are considered quite essential for functional programming.
I would doubt that. Surely, things like Numpy are written in a functional fashion, but Python relies very much on statements, iteration, things not being an expression, almost every named symbol except string and number literals being mutable, and there are no block-scoped name bindings which are essential to functional languages.
And the attempt to add the latter to Python might end in a far bigger train wreck than C++ is already.
Mixing OOP and functional style works, more or less, for Scala, but everyone agrees that Scala is a hugely complex language. And in difference to Python, it has immutable values.
What could turn out better would be to create a new language which runs interoperable in the same VM (much like Clojure runs alongside Java and can call into it). And that new language, perhaps with the file extension ".pfpy", would be almost purely functional, perhaps like a Scheme or Hy, without these dreaded parentheses. That would at least leverage Python's existing libraries.
You can do editable installs with poetry, I do it every day.
Just run this: \rm -rv dist/; poetry build --format sdist && tar --wildcards -xvf dist/.tar.gz -O '/setup.py' > setup.py && pip3 install --prefix="${HOME}/.local/" --editable .
More details here: https://github.com/python-poetry/poetry/issues/34#issuecomme...
PyOxidizer feels like the big win, but a part of me wonders if the original sin of allowing aribtrary code execution during installs really stops a "wrapper" tool from getting this right. https://pyoxidizer.readthedocs.io/en/v0.9.0/index.html
Packages are tested before installation, and there is no need for hacks like pyenv or broken ruby envs. It also plays nicely with vendor packaging. No sat solving needed, deps are resolved dynamically, powered by simple Makefiles, not special baroque and limited declarations syntax.
So that you don't have to integrate upstream changes continuously... Not a way to build a sane ecosystem if you ask me.
> package selection is much quicker than Python
So is it because it downloads multiple versions of the same dependencies that it's so much slower than pip? Or is there more?
> The Python Software Foundation is receiving $407,000 USD to support work on pip in 2020. Thank you to Mozilla (through its Mozilla Open Source Support Awards) and to the Chan Zuckerberg Initiative for this funding!
Really, the whole distutils is a fancy way to produce a simple zip archive and put it in a well know location in site-packages.
meson has the build figured out, it's just a way of installing that archive with a bit of metadata.
Obviously, pattern matching comes from the ML family and functional Lisps like Clojure. What makes it a difficult integration into Python is that in languages such as Rust, OCaml, Haskell, but also Racket and Clojure, almost everything is an expression, and name bindings are, apart from a few exceptions, always scoped. Consequently, pattern matching is an expression, not a statement.
A similar issue is that Python 3 tried to become more "lazy", similar to how Haskell and Clojure are - this is the reason for replacing some list results with generators, which is a subtle breaking change. Lazy evaluation of sequences is nice-to-have on servers but its importance in Haskell and Clojure comes from them being functional languages which are geared towards a "pure" (side-effect-free) style, in which they differ a lot from Python.
My impression is also that over time, Python has really absorbed a huge number of features from functional Lisp dialects. This might seem surprising. Well, here are some things that modern Lisps like SBCL, Schemes and functional languages on the one hand side, and Python 3 do have in common:
* a Read-Eval-Print Loop (REPL)
* strong dynamic typing
* automatic memory management
* memory safety
* exceptions
* a wide choice of built-in data types: lists, strings, vectors, arrays, dictionaries / hash maps, tuples, sets
* keyword arguments and optional arguments in functions
* handling of names in scopes and names spaces
* closures and lambda functions
* list comprehensions
* pattern matching (limited support for tuples and lists in Python)
* Unicode strings
* arbitrarily long integers
* complex numbers
* rational numbers
* number type are part of a hierarchical type hierarchy (numeric tower)
* empty sequences, containers and strings are logically false
* support for threads (but no real parallelism in Python)
* low-level bit operations (a bit limited in Python)
* easy way to call into C code
* type annotations
* if ... else can be used as an expression
* string formatting is a mini language
* hexadecimal, octal and binary literals
* standard functions for functional programming like map and filter
* support for OOP (e.g. by the Common Lisp Object System)
* support for asynchronous execution
What is notably missing from this list is parallelism (as opposed to concurrency); Python simply does not support it in a practical way, while some functional languages do support it extremely well.
The net result of this creeping featuritis appears to be that Python, which is still classified as "beginner friendly", is now actually significantly more complex than a language like Racket or Clojure, perhaps because these features are often not integrated that well. I even think that Rust, while clearly being targeted at a very different domain, is more streamlined and well-composed than Python.
What is also worth mentioning is that these functional languages have seen steady improvements in compilers and performance of generated code, with the result that Rust code is now frequently at least as fast as C code, SBCL is within arms reach of C, and Clojure and Racket are about in the same league as Java - while Python code in comparison continues to be extremely slow:
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
Early Python was inspired by ABC and C. ABC has a Python-like REPL, strong dynamic typing, automatic memory management, memory safety, a nice collection of built-in types, arbitrarily long integers, and rational numbers. C has low-level bit operations, (an easy way to call into C code,) a ternary expression-level if-else operator (and make no mistake, Python's expression-if is a ternary operator that's distinct from the statement-if-else), and hexadecimal and octal number literals.
There is at least a little influence from functional Lisps (Mypy lists Typed Racket as one of its influences), but a lot of what you list was taken from different languages, or is distinctly un-Lisp-like in Python, or was in Python from the start rather than absorbed over time, or is just obvious enough to put in a very high-level language to be reinvented.
It's also important to distinguish between internal complexity and user complexity. Arbitrarily long integers are complex to implement, but easier to use than fixed-length integers. Even features that do have a lot of user-facing complexity can be very easy to use in the common case. Python is hideously complex if you explore all the tiny details, but I'm not sure that it's all that complex to use. But I haven't used Clojure and Racket so I can't really comment on them.
> I even think that Rust, while clearly being targeted at a very different domain, is more streamlined and well-composed than Python.
I think I agree. But Rust has the benefit of only dealing with a measly five years of backward compatibility. Python has accumulated complexity, but the alternative would have been stagnation. If Python hadn't significantly changed since 1996 it would be more streamlined but also dead.
> What is also worth mentioning is that these functional languages have seen steady improvements in compilers and performance of generated code, with the result that Rust code is now frequently at least as fast as C code
I don't think Rust suffers from the issues that make functional languages hard to compile, so that might be a bad example. In Rust code it's unambiguous where memory lives. It has functional features augmenting a procedural model, rather than a functional model that has to be brought down to the level of procedural execution. So it might be "merely" as hard to optimize as C++.
As an unrelated fun fact, Common Lisp has more low-level bit operations than C, such as "and complement of integer a with integer b" or "exclusive nor":
http://www.lispworks.com/documentation/HyperSpec/Body/f_loga...
It also has logcount, which is the counterpart to the implementation-specific popcount() in C.
Here, Python clearly borrows from functional languages. And there are basically two families of functional languages: Strongly and statically typed languages like ML, OCaml, Haskell, Scala, F#, and on the other hand, dynamically typed Lisps and Schemes.
My point is that all these adopted features are present in the latter category.
The issue is that in functional languages, the compiler has more information and can reliably rely on more assumptions, thus it can make more optimized code. This is why also Common Lisp can compile to very fast code (in a few of the cited micro-benchmarks, faster than Java).
You just need to follow the mailing lists [1] and see that many core developers themselves are caught by some namespace abnormality.
It is a pity that Greenspun's 10th rule is in full effect again and we're stuck with an inferior Lisp/ML, especially in the scientific sector.
[1] Or rather the archives, since they are now de facto corporate owned. There is no free discussion any more and people are afraid to post.
You will love Julia.
Here are some links:
https://julialang.org/blog/2012/02/why-we-created-julia/
Julia: Dynamism and Performance Reconciled by Design (https://dl.acm.org/doi/pdf/10.1145/3276490) <= This is great and surprisingly approachable.
https://opensourc.es/blog/basics-multiple-dispatch/
And when you start finding things that you miss, Julia and the community got you with excellent Metaprogramming support.
https://github.com/thautwarm/MLStyle.jl
However for C++, I think that corporatization is having a strong negative influence on the language, which leads to it being stuffed with poorly integrated features which nobody really overlooks any more.
https://twitter.com/mildmojo/status/1354514025414066178?s=20
https://twitter.com/szferi/status/1352208874657472512?s=20
https://www.reddit.com/r/Python/comments/kfxibk/pypi_xmlrpc_...
And relatedly they have a massive spam package problem:
https://www.zdnet.com/article/pypi-gitlab-dealing-with-spam-...
NOT_FOUND = 404
match get_status():
case NOT_FOUND:
# this actually assigns to the global NOT_FOUND
# and is effectively the default case
case _:
# this never gets triggered
Yeah, I agree that's a bit ugly. But you can apparently do this: class Status(Enum):
NOT_FOUND = 404
match get_status():
case Status.NOT_FOUND:
# works as expected
...
And really how is any of that more ugly than this? def func_with_default(foo={}):
if "bar" not in foo:
# "bar" is set in the module-level dict that
# was initialized when the func def was parsed,
# not in a dict that is created per call
foo["bar"] = ...
...
And we've been living with that one for years. These are just the things that you have to learn when you start using Python, just like any other language.I, for one, am excited to start using this syntax.
Pattern matching is a desired feature, but the shortcomings are too costly for what it provides. You just outlined yourself the quickest foot-gun I've ever seen.
My second problem is that this violates many of the invariants you rely on while programming Python. f(x) always gives you the value of applying f to x. Nope, not in case. | means bitwise or. Nope, not in case. a means the value of a. NOPE. Not in case.
Why would it need to copy anything? What's wrong with just evaluating the default argument expression every time the function is called with a default argument rather than once at definition-time? That's how it works in other languages.
And I think the ship on '|' has sailed with the dictionaries.
edit: updated list name since pipe ("|") and small L ("l") look kind similar in the code snippets.
Why would it be a problem to do a copy in this case?
> f(x) always gives you the value of applying f to x
Not if it is preceded by "def"
> | means bitwise or.
Not if it had been overloaded, like many popular libraries do.
> a means the value of a
Not if it is followed by "="
How is that different from the new pattern matching syntax ?
How are copy semantics even defined unambiguously?
> Not if it is preceded by "def"
In that case it is analogous, def f(x) DEFINES what f(x) means. For class definitions it's different, and it is indeed debatable if `class A(SuperClass)` is good syntax. I would have preferred `class A from SuperClass`, but that ship has sailed.
> | means bitwise or. Not if it had been overloaded, like many popular libraries do.
You missed the point willingly I think. See sibling comment. You cannot overload its meaning in a match, and the meaning is not related to what it otherwise means (bitwise or, set union, etc.).
> a means the value of a Not if it is followed by "="
And again, this is by analogy. a = 1 means that you substitute a with 1 wherever a occurs. Not so with the pattern matching syntax. If we had a = 1 then a == 1. Where is this analogy for pattern matching? How do you even make the comparison? You do not.
All of your counterpoints have reasonable analogies within the syntax itself (eg: the inverse of a function call is a function definition).
NOT_FOUND = 404
match get_status():
case NOT_FOUND:
print("Here")
# this actually assigns to the global NOT_FOUND
# and is effectively the default case
case _:
# this never gets triggered
print("There")
I got a meaningful error: File "<ipython-input-13-5264d8327114>", line 3
case NOT_FOUND:
^
SyntaxError: name capture 'NOT_FOUND' makes remaining patterns unreachable def f(x):
return 1
y = x + 1
return yNot entirely surprised by the negative responses and I can see there are gotchas here, which is always thorny. But everyone seems to be picking simple uninteresting use cases so they can knock then down.
This feature would seem to be for cases where you need to do more complex matching.
In terms of the variable assignment, surely the whole point of this feature is to give you nice assignment based on matching, rather than using it as an if or switch statements?
It's not about ugliness, it's about clarity and robustness. It's about not ingraining landmines into the language, whether beautiful or ugly. This is just asking to be blown up in people's faces over and over again.
I suppose there's an obvious flaw to that behaviour, though.
case == FOO: case is True:
That was part of PEP642, but it ended up containing more other questionable things. I hope that particular point will be separated and implemented.
It's not a "module-level dict", you can create functions inside other functions:
def foo():
def bar(a={}):
...
return bar
Each instance of bar gets its own dict when you run foo() and the "def bar(...): ..." statement gets executed. The dict is packaged up inside the function object (sort of like a closure except that the dict and it's name aren't from the enclosing scope of the function, and of course you can "shadow" it by passing in an argument for the parameter. https://en.wikipedia.org/wiki/Closure_(computer_programming) ) match status:
case 404:
return "Not found"
not_found = 404
match status:
case not_found:
return "Not found"
The first checks for equality (`status == 404`) and the second performs an assignment (`not_found = status`).Couldn't we achieve the same functionality with a little less ambiguity using the following syntax?:
not_found = 404
match status:
case not_found:
return "Not found"
case _ as foo:
do_something(foo)
return "Match anything"
it even works for the example in PEP 365 match json_pet:
case {"type": "cat", "name": _ as name, "pattern": _ as pattern}:
return Cat(name, pattern)
case {"type": "dog", "name": _ as name, "breed": _ as breed}:
return Dog(name, breed)
case _:
raise ValueError("Not a suitable pet") match subject
case [first := _, rest := _]
return [rest, first]I would have preferred `as` instead of the walrus operator too.
There are 100s of things in Python who would be confusing to people used to other languages, this is not one of them.
It's not a switch! Nowhere does it say switch. It's structural pattern matching!
EDIT: The lack of block scoped variable thing does seem like a wart right enough.
I actually replied to the wrong comment after reading several that visually looked similar at the time, so apologise for causing confusion in this subthread.
This is not specific to "match" statement, but is a general issue in Python. And thus, needs to have a general solution, orthogonal to pattern matching. Are you interested? Please post to the python-ideas mailing list.
I might be misreading the grammar but it looks like you can produce the desired effect by using an attribute, e.g. the following would perform an equality check, not an assignment:
match status:
case requests.codes.not_found:
return "Not found"
The tutorial seems to confirm this: "This will work with any dotted name (like math.pi). However an unqualified name (i.e. a bare name with no dots) will be always interpreted as a capture pattern" match status:
case not_found:
return "Not found"
capture success_code:
return "Returned success code: %s" % success_code
or the "_ as x" or a myriad other ways to make capture explicit... match response:
case (not_found, msg := _):
return f"Not found: {msg}"
case (error, "No swizzle available"):
return "We lack swizzle. :-("
case pair := (_, "Swizzle"):
log(f"Unexpected swizzle: {pair}")
return f"Swizzle?"
case ((code := _), _):
return f"Success: {code}"Now think what will happen if you need to move that not_found variable to the same file as that code (so it will no longer be a dotted name). If you do it manually you need to be extra careful, if you use an automatic tool either it will reject the change or will need to create a dummy class or something in the process.
match status:
case == not_found: # Check for equality
...
match status:
case as not_found: # bind status to variable not_found
...
At least the former should be an option instead of using a dotted name IMO.You know, a lot of potentially confusing behavior would be avoided if programming languages had the sense to make variables read-only by default and disallow variable shadowing altogether.
Compared to having two versions of the same name, one shadowing another?
In other languages that support match, whether functional or not, you are not changing the value of the variable, but you are shadowing/rebinding the identifier inside the scope of the match clause.
Many of the comments here reveal a bizarre parochialism.
let x = foo
in (
case bar of
x -> x,
x
)
This will give `(bar, foo)`: for the first element the `x` in the case will match against `bar` and return it, then that `x` will be discarded as we leave its scope; the second element uses the binding of `x` in the `let`.According to the Python semantics we would get `(bar, bar)`, since we only have one `x` variable. When the case pattern succeeds, the existing `x` is updated to refer to `bar`. Hence we get the `bar` we expect in the first element, but we also get `bar` as the second element, since that `x` variable was updated. (Note that Python guarantees that tuple elements are evaluated from left to right).
No, its not, but no language (at least that I am aware of) except python does pattern matching + local variables + not introducing a new scope with the pattern match.
Ruby is the closest, but it does introduce a new scope while providing a mechanism for binding variables in the containing local scope. (As well as a method to “pin” variables from the containing scope to use them in matches.)
> (As well as a method to “pin” variables from the containing scope to use them in matches.)
This is a good idea, I agree -- at least for Python, where you would obviously just call __eq__.
EDIT: It looks like you actually can match against constants with this PEP, as long as you access your constant with a dot (e.g., HttpError.NotFound). This seems like a perfectly reasonable solution to me.
This seems like a bizarre misunderstanding of Python scoping rules, and how this can be a problem here.
I would NOT expect for the line “case not_found:” to reassign the status variable to 404 regardless of what it was before.
I can’t see how or why that would be intended behavior.
That's what it looks like, but no, the refactoring really does change an equality test into an assignment.
len([]) = 0 len([first|rest]) = 1 + len(rest)
That's a trivial example. The second PEP (pattern matching tutorial) has several other examples:
https://www.python.org/dev/peps/pep-0636/#matching-multiple-...
So, if you use a variable in a pattern, it's an implicit assignment. If you use a literal, it's a value to be matched against.
I agree that the trivial case (a single variable with no conditions) may be confusing before you know what's going on, but I think the alternative, where a single variable is a comparison but multiple variables (or a structure) is an assignment isn't necessarily better.
I would clarify that to implicitly introduce variables.
Consider the following:
$ python3
Python 3.8.6 (default, Dec 28 2020, 20:00:05)
[Clang 7.1.0 (tags/RELEASE_710/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(x):
... return ([x for x in [1, 2, 3]], x, (lambda x: x+1)(x), x)
...
>>> foo(42)
([1, 2, 3], 42, 43, 42)
The list comprehension did not assign the variable x to 1, 2 and 3; it introduced a variable called x, but our original (argument) variable is unaffected (since the second result is 42). Likewise, the nested function doesn't assign its argument variable x, it introduces an argument variable x. Whilst this affects that nested function's result (we get 43), it doesn't affect our original variable, since the final result is still 42.This match syntax seems to be assigning, rather than introducing, which is a shame.
I also think the same as you wrote, the second check will be a hard to spot mistake
To be honest, I feel I like the (sort-of-) "forced namespacing" of matching constants this brings. It should be an easy habit to discipline too, the rule being very simple:
"if you don't want to use literals in your matching, you must plug them in an enumeration"
Too bad that enumeration can't be a PEP 435 enum without adding an ugly `.value` accessor to each case, though.
> The implementation may choose to either make persistent bindings for those partial matches or not. User code including a match statement should not rely on the bindings being made for a failed match, but also shouldn't assume that variables are unchanged by a failed match. This part of the behavior is left intentionally unspecified so different implementations can add optimizations, and to prevent introducing semantic restrictions that could limit the extensibility of this feature.
That's basically dynamic scoping instead of lexical scoping only inside the match blocks and only for pattern variables. Who in their right mind comes up with a design like that? That's the javascript route! I get it that proper binding would have been difficult but if language design is too difficult, you should stop and not go one like you don't care about the consequences! This decision will waste thousands of developer hours when searching bugs!
Isn't this more or less what was the argument to allow more undefined behaviour in ANSI C ?
(Edit: I think this also comes from the tension caused by integrating features from functional languages into an imperative language, like explained in more detail here: https://news.ycombinator.com/item?id=26086863 )
Python is big time SLOW, there's a ton of untapped optimisation potential before wandering into UB for sake of speed territory.
The essence of the issue you quote is that Python needs block-level scope for variables (in addition to the standard function-level scope). Similar to what JavaScript acquired with "let" and "const" keywords. That's more pervasive issue than just "match" statement of pattern matching, and thus better handled orthogonally to it.
No, it's not. I mean, sure, either general or special-case (like comprehensions already provide, and there is no good reason for matches not to) isolated scope would solve this, but so would bind-on-success-only with existing scoping.
In this case, would it not better to fix block scoping first, and introduce the pattern matching feature later?
Also, this is by far not a easily agreeable issue because changing this will break a lot of ugly but working imperative code. This has easily more impact than changing the default string type to Unicode.
For me, adding pattern matching before defining scoping feels like a technical debt issue in a large code base - if you make a change that depends on an improvement, it is much cleaner to make that improvement first.
Also, Python has only one widely-used implementation, and arguably it will be difficult to change behavior of that implementation if people did came to rely on a certain scoping behavior.
No, it's not a scoping change, the variable in the pattern is definitively in the scope (function or module) containing the pattern match.
It's just non-determinism (or, no specification) as to what, if anything, gets assigned to it as a result of the failed pattern match.
another pylint rule to forbid using same names outside match clauses and inside.
Bike shedding at its worse
Controversial is correct. A poll showed a majority (65%) of core developers opposed to this particular proposal, and a plurality (44%) opposed to pattern matching altogether.
https://discuss.python.org/t/gauging-sentiment-on-pattern-ma...
* A majority (56%) of responders want some form of pattern matching.
* Exactly half of all responders, forming nearly 90% of the above majority, are fine with that form being PEP 634.
* There are differing opinions about supporting PEPs, but a supermajority (70%) of those who agree with PEP 634 are fine with it alone.
The fact that it was possible to express more nuance when agreeing with PEP 634 shouldn't diminish their voice against those who reject the idea altogether.
If you decide to act on this 34% anyway, you are only just telling your community that their opinion doesn't really matter. Which might explain why 60% of the eligible voters did not bother.
agreed. I'm being pedantic on more specific conclusions, but it wasn't the best move. Even if I'm somewhere between "fine" and "happy" about this, personally.
That half includes those who voted for "accept 634 + 640" or "accept 634 + 642", whom I doubt are entirely happy with the decision to accept PEP 634 and reject 640 & 642.
That said, I interpret this part:
> PEP 642’s proposed syntax does not seem like the right way to solve the jagged edges in PEP 634’s syntax
to mean that this is merely an initial spec. Those unhappy with the syntax can avoid using it for now, there are no breaking changes. It took a couple iterations to refine the async syntax too, remember, and (IMHO) we arrived at a clean-enough version of it. I have hope!
An explicit "do not care" or "none of the above" option in that poll would have shed more light into this.
People that contribute are not infinite and those initial more active contributors get demoralized supporting work over a moving foundation.
Why not put up an effort on speeding things up, removing the GIL. Important and stale issues of the language that users really care about. F strings where good tho. That’s it. Async syntax? Less good. This pattern matching thing? Have fun debugging this.
Firefox suffered greatly in marketshare because they didn't pull the plug soon enough but rather gained a reputation for slowness and bugginess. Doing nothing isn't a viable strategy when you have competitors (ie: Chrome) who are doing something.
I _love_ that I can install an extension without restarting, and as much as I sympathize with the pet projects that got dumped, I think it would have been a huge mistake to hold that up just to keep dead extensions in zombie mode rather than grave mode.
Why? How many times do you install extensions that restarting the browser to see them would be a concern?
You are making it look like there is nobody working on those things but there is actually multiple core devs trying to making Python faster.
Really, after 3.8? I thought 3.5 was a golden era?
> Why not put up an effort on speeding things up, removing the GIL.
That's exactly what requires corporate backing (removing is easy, fixing all the breakage it causes takes a lot of time and effort).
Because if I didn't misunderstood, this is not correct, is it?
NOT_FOUND = 404
OK = 200
match getCode():
case NOT_FOUND:
return default()
case OK:
return response()This along with mutable default values is going to be one of the nastier Python warts.
match event.get():
case Click(position=(x, y)):
handle_click_at(x, y)
case KeyPress(key_name="Q") | Quit():
game.quit()
where `Click(position=(x, y))` is not at all what one would expect.What I still don't understand is: does the new syntax magically do this to a user-defined class? i.e. if I say
foo = Click(position=(x, y))
vs ...
case Click(position=(x, y))
those identical expressions, for the same value of Click, have widely different semantics?edit: typo fix
This is already special-cased in the standard library for, say, set union (where admittedly the concept is more similar to bitwise or).
> Patterns may use named constants. These must be dotted names to prevent them from being interpreted as capture variable:
NOT_FOUND would always match as a capture variable, so you'd always return default().
I fully expect this to be covered by linters, but not with further language support.
NOT_FOUND = 404
m = {"NOT_FOUND": NOT_FOUND}
match value:
case m["NOT_FOUND"]:
pass NOT_FOUND = 404
match value:
case v if v == NOT_FOUND:
pass
On its own this is a convoluted alternative to `if`, but it can be useful when we have lots of patterns.Alternatively, we can avoid using a separate `v` variable and just use `value` directly:
NOT_FOUND = 404
match value:
case _ if value == NOT_FOUND:
pass
We can even match on a trivial value, and do all of the interesting checks using guards: NOT_FOUND = 404
match None:
case _ if value == NOT_FOUND:
pass
This latter form acts like Lisp's `cond`, and I've used it a few times in Scala, e.g. () match {
case _ if foo > bar => ...
case _ if foo < bar => ...
case _ if foo == bar => ...
} (define not-found 404)
(match status
(,not-found (do-stuff))
(else (display "you might believe this is an else clause, but it actually just matches everything and binds it to else")))Like other comments have said, I loved and learned a lot of Python from looking at a code base and understanding everything immediately because there wasn't much to learn on the language end of things. It was nice and small. Not that the addition of pattern matching is a death sentence for simplicity, but I fear that it may lead to some other extraneous features in the future.
I like powerful, featureful languages, but I personally like Python as a simple language that anyone can learn 80% of in a busy weekend.
Will I use pattern matching? Maybe. I'll definitely play around with it. Now if we could get some algebraic datatypes then I think I'd start contradicting myself...
> I'm going to submit a PEP to add a kitchen sink to Python.
I personally would opt for the sink with the snake, as it is more Pythonic, despite not being the nicest and cleanest solution (is that a Pythonic property as well?).
It looked like this: https://www-archive.mozilla.org/docs/web-developer/samples/k...
This is why I'm still enamored with Lisp. One doesn't wait around for the high priests to descent from their lofty towers of much deep pontification and debate with shiny, gold tablets inscribed with how the PEPs may be, on behalf of the plebes. One just adds new language feature themselves, eg. pattern matching[1] and software transactional memory[2].
We also know that they don't always make things clear, so we don't use them everywhere. Programmers using languages that have a pattern matcher "built in" tend to use it all the time, and it's not always a pretty sight. I conjecture that with this addition, Python codebases will become dichotomized: either it will be used everywhere, or it will not be used at all. The latter obviously has a head start :)
New syntax is often a bad idea, but sometimes it's a really good idea. It'd be good to allow experimentation in the wild, and potentially upstream these features later once they've been proved out.
This is why I suggested macros as the feature I'd like to see most in the last python developer survey. Most of the time, defining a macro is bad idea and is a code smell, but sometimes they add very useful language features.
def handle(command):
match command.split():
case ["quit"]:
print("Goodbye!")
quit_game()
case ["look"]:
current_room.describe()
It'll be a bit odd, though. parts = command.split()
if not (0 < len(parts) < 3):
raise TypeError(...)
cmd, arg = parts
if cmd == 'quit':
...
elif cmd == 'get':
character.get(arg, current_room)
elif ...:
...
For more advanced examples, you'd use dictionary dispatch anyway. Will this syntax work with numpy? (match command
(("quit") (display "Goodbye!"))
(("look") (describe current-room))
(("get" obj) (character-get obj current-room))
(("go" dir) (set! current-room (room-neighbour dir)))
(_ (display "Invalid command")))in this case pattern matching would have helped
That proposal, to deliberately hobble pattern matching by making it a statement, was an egregious ideological campaign with genuinely absurd consequences.
I don't write much Python these days, but it being a statement rather than an expression is disappointing
It forces you to use a separate "output" variable or `return`.
x = (a if c else b)
is an expression, where the conditional equivalent if c:
x = a
else:
x = b
is a statement.https://www.python.org/dev/peps/pep-0636/#adding-conditions-...
Yet it can't be used in a lambda, it can't be assigned to a variable, it can't be used as an argument, it can't be called as a function, it can't be put in a datastructure, it can't be raised, it can't be returned, it can't be yielded, and so on for all the things that can't be done to statements.
Heck, we can't even match on a match!
I maintain a transpiler that converts python to 6 type safe languages. Keeping match semantics similar makes it easier to transpile.
Pattern matching is great for dispatch and overloading, but because it's a statement there's no way for users to add overloads.
There will have to be some `matches(pattern, object)` function in CPython. Why not make this available to users? Why make patterns syntax, not objects?
My initial take upon stumbling upon the controversy was "why would pattern matching be bad?" because I have only experienced it through the lens of C# 9.0. Upon reviewing PEP 622 and looking at some examples of usage... I am in agreement with the detractors. This just doesn't seem to make sense for python, but I would certainly hate to get in the way of someone's particular use case as long as the new feature doesn't fundamentally cripple the language for others.
IMO, Microsoft nailed it with their pattern matching implementation:
https://docs.microsoft.com/en-us/dotnet/csharp/pattern-match...
Not because mypy is bad per se, but it just doesn't flow into a Python workflow naturally. Every time you try to interact with an external module without these annotations you immediately lose all the advantages of statically typed programs.
For me, Python with annotations just doesn't make sense, at that point I would prefer to program in Rust or Java.
Most importantly though, it does not make Python statically typed, by no means. It just lets you lint stuff in a semantic fashion (which is helpful, no doubt), improves auto-completion and removes the need of listing type requirements in docstrings.
But like... hey, finally get a case statement! I imagine the community will coalesce a bit around best practices. And stuff like pylint will catch name shadowing (at least in theory). Almost all pattern matching mechanism have name shadowing issues and it's definitely annoying, but they are able to figure it out.
But I don't see that, or any other solution for local variables, in the PEP
Having a dedicated syntax would mean someone could look at the patterns I'm matching and see clearly what the format of the input should be. This seems ideal for handling various user-friendly toml/yaml/json configuration formats and other semi(poorly)-structured data.
I think it also addresses a real weakness in OO: to add behavior per class you either lard up classes with not-really-relevant methods, or create a proxy class, or do the inevitable if/elif isinstance chain.
Edit: Actually that's already true with string formatting.
(1) It doesn't make the language less efficient
(2) The new feature is coherent with the rest of the language
(3) It doesn't make learning the language harder
(4) It brings joy in my life (as f-strings do)
Then.. it's ok :-)
- Tooling, code analysers, etc. have to be updated to understand the new features. Tools which are dead or "finished" may stop working.
- The possibility that someone might use a new feature can break guarantees that are relied upon by existing code. An obvious example would be adding try/catch to a language: in languages without this, a function call is guaranteed to either return control to us, or to run indefinitely. Libraries might rely on this to clean up file descriptors, etc. afterwards. Such libraries would be broken by the mere existence of try/catch; even if we never actually use it.
That said, I'm a big fan of pattern-matching, so it would be nice to have in Python, rather than crude approximations like '{pattern1: A, pattern2: B, pattern3: C, ...}[myVal]'
[0] https://discuss.python.org/t/gauging-sentiment-on-pattern-ma...
Time to refactor the project I am currently working on that is loaded with `str.format()`
s = "this is {}"
print(s.format("possible"))
but you cannot do that with f-strings because they are resolved on definition, so you could do something like this: for message in messages:
print(f"The message is {message}")
But not this: s = f"The message is {message}"
for message in messages:
print(s)
This is the same drawback of JavaScript's Template Literals [0].EDIT: Fix syntax in examples.
[0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
x, y = 1, 2
print(f'{x=}, {y=}')Three string formatting approaches are all in wide use. There are now two different ways to do something as fundamental as assignment. Some classes use explicit methods like __eq__, others hide them by using @dataclass. Async-await adds coloured functions [0], along with “red” versions of numerous language constructs.
That’s not to mention type annotations, which I won’t deny are popular but are incredibly complex.
[0] http://journal.stuffwithstuff.com/2015/02/01/what-color-is-y...
But... after I learned Scala a bunch of years ago, working in any language without pattern matching has felt like significantly more of a chore than it used to be. It's like you've been doing something the hard way for years, someone teaches you an easier, better, more readable way, and just when you get used to it and love it, then tells you that you can't use it anymore.
Certainly that's not true of all possible high-mental-load new features that could be added to Python. But I don't want to believe that features that drastically increase ergonomics shouldn't be added to a language because they make the language less simple.
Too much mental overhead. Other people love that kind of stuff though.
Within a few seconds I tested that theory, by populating a list with dicts and voila - just worked. Close to the last day I ever touched Perl.
The python language expansions that have come recently, f-strings, walrus operator, and now matching - are great in that they don't make the language more complex - all three of these are easily explainable in a few minutes to the novice, and once they understand it, they can quickly (and profitably) incorporate it into their code.
I wan't there to be a steady drumbeat of these improvements that let me write more elegant code, more concisely.
Try and find a single python developer who would give up their f-strings now.
I still use, and love Perl. If you stick close to the original inspiration of using it to process text, it flows very naturally and isn't hard to read or understand.
I do get that the proliferation of sigils ($,@,%), breadth of built-ins, things like $_, complex dereferencing, and overall terseness are a visual putoff.
It may be that I still like it because it uses mostly the same functions as 'C'...things like stat(), getpwent(), ioctl(), and so forth that were already in my head. And it was way less tedious for strings and text, and no malloc/free to keep track of.
Isn't there supposed to be only one obvious way of doing these things?
I think the advantage of switch statments and pattern matching is that you know the scope of the thing you're switching or matching on, but you don't have that restriction in if/elif/else blocks. There's nothing keeping me from adding a condition like, `elif day == "Tuesday":`, that has nothing to do with the task at hand. When I see switch or match, I feel like I know what I'm getting into.
Brainfuck is an extremely simple language. I mean, it's perfect. Only 8 instructions! Only 1 pointer! Turing complete! Why isn't everyone writing their code in this language?
A bicycle attached to a wheelbarrow is extremely simple transportation. You can get anywhere you need to go, you can carry heavy loads, it's easy to use, easy to fix, cheap. Why would you use anything else?
Wood is a great building material. You can build a building several stories tall, it's cheap, plentiful, easy to work with. We should just standardize all construction on wood.
Water is the simplest beverage. It's clean, healthy, easy to ship, easy to store. We don't need to drink anything else.
That's a funny one. The whole history of C++ is being backward compatible, originally with C.
f'gcd({a}, {b}) = {math.gcd(a, b)}'
is so much better than 'gcd({}, {}) = {}'.format(a, b, math.gcd(a, b))
In the .format() version, the formatting and the values are separate and that makes it more clear to see both the formatting and the values. I really like that separation. When the expressions get more complex, .format() doesn't really lose any clarity while f'' gets pretty unreadable quite fast IMO. Yes, you can simplify by assigning the expressions to variables, but .format() doesn't even need that.And I really dislike format where the arguments are given by position. For short strings it's not going to matter but for long strings you're bound to mess something up sometime. Just imagine writing some kind of long email template and ending up with something like:
'''Dear {}{}
I write you on the {} to inform you...
Kind Regards,
{}'''.format('Mr. ', 'President', '1st of April', 'Ohio', '12', ..., 'Automated mail bot')
Okay it's a bit contrived but any long multiline formatted string is going to be hard to read without using keywords.And once you insist things are named then f-strings look a lot neater since you get:
f'gcd({a}, {b}) = {math.gcd(a, b)}'
v.s. f'gcd({a}, {b}) = {gcd_a_b}'.format(a=a,b=b,gcd_a_b=math.gcd(a, b))
Of course sometimes a template is the appropriate tool, but usually because it's going to be used more than once.It makes it harder to see which values actually go where though. I really dislike the separation.
Like you - and I just learned about the existence of f-strings tonight - I find .format() to be much more readable and logical than f-strings.
My first impression reading about f-strings was "ew."
It's not a case of "I don't like it because it's new". To my jaundiced and admittedly subjective eyes, I'm still finding .format() better, precisely because it doesn't lose any clarity in exactly the way you stated.
In other words, I just don't get the point.
Furthermore! f? Really? What the f does f mean? The str() function is the str() function. As well as print(). As well as .format().
f? please
>>> a, b = 2, 4
>>> f"{math.gcd(a, b) = }"
'math.gcd(a, b) = 2'Is that enough?
Find me a modern language where that isn't true, though.
"There are only two kinds of languages: the ones people complain about and the ones nobody uses."
I think it's an interesting point you make, because Python is actually one of the few languages that tried to break away from its past (the whole 2.7 to 3.7 fiasco), but it seems the need for a language to be stable is just much, much greater – so features are just piled onto the existing standard instead.
If COBOL taught me one thing, it's that I'm pretty sure in 60 years time there will still be critical infrastructure running on Python 2.7.
My old boss used to say this thought terminating cliche whenever I encountered a problem with PHP. It's a rather useless form of binary thinking, since it completely ignores scale and severity.
It's similar to statements like "all politicians are bad", which put the likes of Nick Clegg in the same bag as, say, Pol Pot. It's counter-productive to any meaningful discussion.
In most cases I have encountered people uttering this quote they were using it as a mere observation of the statistical fact that a large group of users will inevitably lead to a larger amount of complaints. And the conclusion was usually something like: "Don't blindly disregard a language, because many people hate it. Always take a closer look if the tool is up to the job."
You may also be interested in: "there are 10 kinds of people - those who understand binary, and those who do not"
Java => Kotlin is an example of a migration that's relatively painless, by design, and lets you incrementally convert projects over, source file by source file. But the Kotlin designers intentionally left alone certain misfeatures of Java to make that happen. It's still UCS-2 rather than UTF-8, for example, and it syntactically papered over nulls rather than actually fixing them with a true Optional monad like more recent languages, and its coroutine/async/await semantics aren't as elegant as Go or ES6 or Python 3.6. Changing runtime semantics of an existing language ecosystem is hard.
C++ is a wholly different beast. Template metaprogramming achieves great things, but at significant cost to readability.
(Python 3 got rid of old-style classes and made the two syntaxes equivalent.)
example: pylint-type tools that flag old ways of doing things, and suggest replacement syntax (e.g. https://pycodequ.al/docs/pylint-messages/r1717-consider-usin... )
My first thought whenever someone proposes changing a language is "could that be done with a library instead?". If it's possible then I think libraries are preferable to language changes; if it's not possible and we decide to change the language, then it may be better (if possible) to make a change which fixes whatever prevented us from implementing such a library. Only if we can't do that would I resort to adding individual features to the language.
For example, Scheme has really good pattern matching, despite it not being part of the language. In fact, there are so many pattern matching libraries for Scheme that there are now attempts to standardise their APIs https://srfi.schemers.org/srfi-200/srfi-200.html
I hate how different reading C++0x and C++17 is. I hate reading a "C++ style guide" for a new project.
I already feel that pretty soon, "Python Style Guide" will be a necessary evil...
Might be that the whitespace indentations focus the mind. Also: PEPs already act as style guides. And if you are worried to do it wrong, just run it through a code formatter like black. It really isn't that much of a problem IMO.
And it looks like Python is heading in the same direction. It's not difficult to imagine a future where some Python projects are going to want such guides too.
I'm quite pleased and also laughing my ass off. Vindication!
Now this doesn't quite apply to cPython, of course, and even PyPy is written in RPython, not Python 3, (correct me if I'm wrong on that, eh?) so it doesn't quite apply to that either.
Every time newfangled geld like this comes down the Py3 turnpike I think of all the other Python implementations that either have to implement it also or get left behind: PyPy, Cython, Jython, Brython, Skulpt, Stackless, Pyjs, IronPython, PythonNet, MicroPython, Nuitka, ShedSkin, Transcrypt, etc., not to mention tools like Snakefood or PySonar or MyPy.
(I'll shut up now, you don't want to hear it. I read the tutorial on the new matching and by the end I found myself chanting under my breath "Cthulhu fhtagn! Tekeli-li! Tekeli-li!")
Yep. You can even get a very nice dev system based on it that's commercially supported: https://astrobe.com/
> Astrobe is a complete integrated embedded software rapid development system running on Windows. It includes a multi-file, fully featured, syntax-aware programmer's editor, native code compiler, linker and builder, program uploader and a serial terminal. Use it to develop reliable software to run on the powerful 32-bit ARM Cortex-M3, Cortex-M4 and Cortex-M7 families of microcontrollers.
You can try out the original Oberon OS workstation in your browser here: https://schierlm.github.io/OberonEmulator/ thanks to a JS emulator for the RISC chip!
Ok, Scala or Rust got a chance. Partial functions (clauses), currying and patterns complement each other remarkably and it is well-researched and formalized for decades.
Unless we keep adding more ways to do the same thing of course.
The zen thing is cited so much because it's often inconsistent the language itself.
https://github.com/RoyalIcing/yieldpattern
It’s amazing to me how much pattern matching, well, matches how I think. A conditional if statement means I have to explicitly read properties off an object or inspect an array to check for what I want. Whereas pattern matching means asking ‘I want something that looks like this’ and do the work for me.
>>> {a, b, z} = {"a": 1, "b": 2, "c": 3, "z": 4}
>>> print(a, b, z)
1 2 4
# to get object attrs we can just do
>>> {someval} = SomeObject(someval=42).__dict__()
>>> print(someval)
42 d = {"a": 1, "b": 2, "c": 3, "z": 4}
match d:
case {"a": a, "b": b, "z": z}:
print(a, b, z)
o = SomeObject(someval=42)
match o:
case SomeObject(someval=someval):
print(someval)
from https://www.python.org/dev/peps/pep-0636/#going-to-the-cloud... and https://www.python.org/dev/peps/pep-0636/#adding-a-ui-matchi...it's more verbose but lets you easily add a default case to catch and handle when a key you expected to be in the dict isn't or the object doesn't actually match the object you expect.
I definitely would have gone for `else:`.
`_` is already used by convention for variables you don't care about, but it's kind mixing things to use it for this too.
The tutorials made it look like `_` is a special case, not just what you would expect putting any arbitrary name there to match no matter what.
If it can be used as switch case on steroids then I am all for it.
Why Python never got switch case is an interesting question.
I'm very glad Python never got C-style switch.
As for Scala, its pattern-matching (among other things!) ultimately comes from ML in the 1970s (its modern descendents being StandardML and Ocaml, and to a lesser extent Scala, Haskell and Rust).
I honestly don't see what this adds over if statements. You save typing `match ==`? I guess indent block is visually more clear than series of ifs/elifs? That's kinda already solved with pep8 styling of separating logic blocks with newlines.
match response.json()["status"]:
case "500":
raise DeadServer()
case "404":
raise BanServer()
vs
status = response.json()["status"]
if status == "500":
raise DeadServer()
elif status == "404":
raise BanServer()
there's some clarity here but at the same time it's an extra indent layer, soon we'll have: class Client:
def download(url):
with open_connection() as session:
while True:
response = session.get(url)
match response.json()["status"]:
case "500":
raise BadServer()
case "200":
return response.json()
As much as I love python's indentation this is getting a bit out of hand, isn't it?
Did we run out of things to add to python?A good example of how pattern matching simplifies code is given in the 'Patterns and Functional Style' section of PEP 635 [1]:
match json_pet:
case {"type": "cat", "name": name, "pattern": pattern}:
return Cat(name, pattern)
case {"type": "dog", "name": name, "breed": breed}:
return Dog(name, breed)
case _:
raise ValueError("Not a suitable pet")
The equivalent if statement would be kind of gross: if 'type' in json_pet:
if json_pet['type'] == 'cat' and 'pattern' in json_cat:
return Cat(json_pet['name'], json_pet['pattern'])
elif json_pet['type'] == 'dog' and 'breed' in json_pet:
return Dog(json_pet['name'], json_pet['breed'])
raise ValueError("Not a suitable pet")
One can imagine extending that to parse 6 or 7 types of messages.Another example is matching tuples or sequences: the equivalent if statement requires checking the length of the sequence, then extracting the variables, etc. The 'case' statement does all of that in one line.
In other words, as one of my university professors would put it: 'there's nothing that can't be written using plain ifs, adds and jumps, but that doesn't mean we all want to write in assembly with just 3 instructions'.
[1] https://www.python.org/dev/peps/pep-0635/#patterns-and-funct...
pet = json_pet.get('type')
if pet == 'cat':
return Cat(json_pet['name'], json_pet['pattern'])
if pet == 'dog':
return Dog(json_pet['name'], json_pet['breed'])
Again it goes against the pep20 which is really the philosophical foundation of the language: "There should be one-- and preferably only one --obvious way to do it."I think the capturing part is the (more) useful one and can save you more typing than your example.
(Yes, I know it isn't "switch"...and yet...)
What remains to be seen is what the execution-time hit might be when compared to other approaches.
from django.utils.translation import gettext as _Different applications but still...my time is limited
Now I just want multi-lined anonymous functions.
I don't share the concerns about simplicity. It is easy to read in my opinion and adds a lot of expressiveness in a relatively straight forward way.
But no, it's just about adding switch to python ... frankly, who cares.
echo "1234foo" | python3 -c 'import re, sys; t=sys.stdin.read(); print(re.sub(r"(\d{4})", "2021", t))'
print($1) if(/^hello (w[^d]+d)/);
Do the same in python and pipe the code to wc -c
Oh, and note the absence of any "import" statement or quotes in the perl code.
Python is not has heavy-handed as C++ for regex parsing, but not by much.
print(/\d{4}/.sub("2021"))
The backslash makes that example a little ugly, but maybe a delimiter other than "/" would work better. It's too bad that r"" is already taken for raw strings.
I think I'm ambivalent towards this. Handling different types of inputs like that is kind of fun. I don't really expect to need to know this one looking at coworkers code in the wild.
I love Python, but as of 2016, I was missing:
0. Pattern matching 1. Easy support for types & type-checking (thanks mypy + annotations) 2. Better string formatting (yay f-strings)
And the nice part is that these are all relatively opt-in features. So excited to be able to using pattern matching as part of the language!
I'll take my down votes. Please move on opinionated HN-ers.
def f(x):
look too close to function invocation for your taste?It's probably inevitable, once you do not have a single person to say no to new features for things that can already be done, that you end up with feature bloat. So, no need to rant about it. But it does effectively demonstrate what the impact of a BDFL is, and what is missing once you don't have one (or at any rate he's not really D any more).