News for hackers. Stuff that matters.
Re:Pattern matching accepted for Python by AlexandrB on Tuesday February 09, 2021 @03:52PM (#26082240)
A lot of early Python's appeal was in its simplicity. I miss that era. Soon Python is going to resemble C++'s bloated feature set where you're not supposed to use parts of the language because "that's the old way of doing things".

Edit: Actually that's already true with string formatting.

Re:Pattern matching accepted for Python by cjauvin on Tuesday February 09, 2021 @04:11PM (#26082422)
I understand your feeling and I would tend to agree for things in other domains.. but for a programming language, I find that if:

(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 :-)

Re:Pattern matching accepted for Python by chriswarbo on Tuesday February 09, 2021 @05:51PM (#26083575)
There are some 'invisible' downsides to adding new features, which often get overlooked:

- 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]'

Re:Pattern matching accepted for Python by pansa2 on Tuesday February 09, 2021 @07:08PM (#26084277)
Pattern matching will definitely make Python harder to learn, though. It’s not particularly coherent with the rest of the language either - the match statement has been described as “a DSL contrived to look like Python, and to be used inside of Python, but with very different semantics” [0].

[0] https://discuss.python.org/t/gauging-sentiment-on-pattern-ma...

Re:Pattern matching accepted for Python by rement on Tuesday February 09, 2021 @04:46PM (#26082772)
I have never seen f-strings! It's my lucky day! https://xkcd.com/1053/

Time to refactor the project I am currently working on that is loaded with `str.format()`

Re:Pattern matching accepted for Python by matt_trentini on Tuesday February 09, 2021 @06:54PM (#26084168)
Take a look at flynt, a tool that can convert older string formatting code to the newer fstring style. I've found it very helpful!

https://github.com/ikamensh/flynt

Re:Pattern matching accepted for Python by aidos on Tuesday February 09, 2021 @07:02PM (#26084234)
Can confirm. I replaced 1.5k instances in our code base in seconds using flynt and it knew the ones that couldn't be swapped out directly. Really great tool. You only ever need it once in your life, but that one time it's amazing.
Re:Pattern matching accepted for Python by andrewem on Tuesday February 09, 2021 @07:51PM (#26084558)
Having not written Python in a long time until recently, I discovered fstrings. Are they the best choice for (nearly all) string formatting at least in new code? They seem to work pretty similarly to eg Ruby’s string interpolation.
Re:Pattern matching accepted for Python by ilovetux on Tuesday February 09, 2021 @06:07PM (#26083727)
Be aware that the only time this won't work is if you need to re-render the f-string with different context. For example you can do this:

    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...

Re:Pattern matching accepted for Python by ZephyrBlu on Tuesday February 09, 2021 @05:50PM (#26083563)
f-strings are truly amazing. They're very painless. The only gotcha I've run into is accessing a dict from inside one. You need to watch out for your quotations :).
Re:Pattern matching accepted for Python by mumblemumble on Tuesday February 09, 2021 @06:57PM (#26084193)
My most recent project makes liberal use of `f"""..."""`
Re:Pattern matching accepted for Python by aldanor on Tuesday February 09, 2021 @07:29PM (#26084419)
Have you seen this? :)

    x, y = 1, 2
    print(f'{x=}, {y=}')
Re:Pattern matching accepted for Python by rement on Wednesday February 10, 2021 @09:28AM (#26089550)
I haven't but that is awesome. That is a much better syntax than just outputting data with `print(x, y)` and remembering which came first (when debugging of course).
Re:Pattern matching accepted for Python by kbenson on Tuesday February 09, 2021 @09:01PM (#26085002)
I find it both incredibly humorous and saddening to see Python devs excited about finally getting string interpolation.
Re:Pattern matching accepted for Python by pansa2 on Tuesday February 09, 2021 @08:16PM (#26084747)
My concern with Python’s feature bloat is the opposite. That there aren’t parts you’re not supposed to use - developers are expected to know all of it.

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...

Re:Pattern matching accepted for Python by roelschroeven on Tuesday February 09, 2021 @04:13PM (#26082443)
And probably other situations, like perhaps corporate environments, where you're not supposed to use the new more advanced parts because not everyone on the team knows them. Python is evolving into several different languages. "There should be one-- and preferably only one --obvious way to do it." Yeah right. I'm waiting for a PEP that deprecates PEP 20, "The Zen of Python". It's become more and more clear that the core developers don't follow it all anymore.
Re:Pattern matching accepted for Python by kelnos on Tuesday February 09, 2021 @07:58PM (#26084616)
First off I'll say that I'm very sympathetic to your point of view, and mostly agree with it.

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.

Re:Pattern matching accepted for Python by mrfusion on Tuesday February 09, 2021 @04:45PM (#26082753)
I thought I’d learn Perl once so I started reading a book on it. I was shocked that literally the bottom half of every page was footnotes. I gave up after a few pages.

Too much mental overhead. Other people love that kind of stuff though.

Re:Pattern matching accepted for Python by ghshephard on Tuesday February 09, 2021 @05:38PM (#26083408)
I was a Perl developer/scripter for the better part of 3 years - wrote a 2-way LDAP<-> HRIS synchronization system in it, complete with customizeable Schemas. Then, 3 or so years into my Perl experience, in which I still needed to look at template code every time I did a HashOfArray/ArrayOfHash, I tripped across some python code explaining how everything was objects.

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.

Re:Pattern matching accepted for Python by kbenson on Tuesday February 09, 2021 @09:11PM (#26085042)
> in which I still needed to look at template code every time I did a HashOfArray/ArrayOfHash

Honestly, that sounds like someone that didn't bother to learn what's actually going on and understand what the language was doing. I mean, that's fine, we all do that... but I wouldn't blame the language for that. Perl makes nested data structures very easy and obvious once you learn what's going on. You just need to actually learn it and not rely on the little shortcuts Perl allows you to use to never make that next step to learning exactly why.

Perl will "just do what you mean" so much that it papers over some of the early learning friction points enough that they build up to a later point. At that point, people either throw up their hands and move on because it's annoying when some shortcut they've relied on isn't working in this one weird instance, or they learn what's really going on (Hint: it's almost always either about understanding references or context at this stage) and it's no longer a problem.

> Try and find a single python developer who would give up their f-strings now.

Things like f-strings and list comprehensions in Python are the exact thing that Python devs used to point out as too complex in other languages (I mean, f-strings look to be pretty much just string interpolation). I think that's evidence that perhaps a language isn't always best suited for all audiences. Python used to be aimed at learning and easy of understanding and use. Now that it's often more targeted for complex engineering projects, you get stuff sneaking in that was specifically avoided by design initially.

Re:Pattern matching accepted for Python by ghshephard on Tuesday February 09, 2021 @09:45PM (#26085233)
"Honestly, that sounds like someone that didn't bother to learn what's actually going" - Yes, exactly! I never learned what was going on. I pinged our JAPH that was kind of my mentor, and asked how he had ever grokked it - and his answer was, he hadn't - he just yanked his template code each time as well.

The point I'm trying to make is not that I'm a good or knowledgeable developer (neither of which I am, despite having written tens of thousands of lines of perl) - but that the core essence of Python, is that people can use it quickly and profitably without being one. The cognitive hurdle to start using objects in python is tiny - and, once you get that - a lot of the stuff that you would hope works, just does. The language is very friendly to novice coders, and it's lack of implicit (for the most part) actions avoids a lot of unclear side effect.

For more complex projects, things like decorators and generators and type-hints, which are advanced, are available if you need them - but you can go a long way (sometimes forever) without ever touching them - that's not the case with simple data structures - you pretty much need to start working with HoA in perl if you want to do complex things, and I know people who have used perl for the better part of a decade, who have never done so - and were blocked from doing more interesting things.

Re:Pattern matching accepted for Python by kbenson on Tuesday February 09, 2021 @11:18PM (#26085703)
That saddens me. It's not actually that complicated, but I think Perl's usage numbers have degraded enough that unless you're frequenting one of the online spots where those knowledgeable about the language gather, you're unlikely to encounter them in the wild anymore, and thus aren't getting a useful explanation.

The simple answer that probably would have solved almost all your problems is that you can use the reference syntax for defining things and it will look like and function the same as JavaScript 95% or more of the time, and the only time you'll need to do anything is when passing it to something that expects an actual array or hash. I mean, you can get away with taking JSON and changing colons into fat arrows and booleans into 0 and 1 and it will just work as a Perl data structure as is like 99.99% of the time. Data structure manipulation works similarly as well for the most part.

Re:Pattern matching accepted for Python by singingfish on Wednesday February 10, 2021 @03:43AM (#26086855)
I've always viewed javascript as verbose crippled perl with good vendor support. I mean, `"use strict";` ...
Re:Pattern matching accepted for Python by ghshephard on Wednesday February 10, 2021 @03:11AM (#26086678)
Oh my goodness kbenson - we had this identical conversation 7 years ago on HN. https://news.ycombinator.com/item?id=7869603
Re:Pattern matching accepted for Python by kbenson on Wednesday February 10, 2021 @04:35AM (#26087187)
Ha, I always wondered how long it would take for me to repeat a conversation here with someone! I figured it was only a matter of time. Now I know how much. :)
Re:Pattern matching accepted for Python by adamc on Tuesday February 09, 2021 @05:52PM (#26083588)
Yeah, this. I love Python, and I hated Perl. Even Java was a pleasure compared to Perl.

At one time, a trainer was trying to tell us Ruby was the new hotness (2009 or 2010, I think). I liked Ruby OK, but Python seems cleaner and we stuck with it. I have not felt the slightest regret.

Re:Pattern matching accepted for Python by singingfish on Wednesday February 10, 2021 @03:40AM (#26086844)
sounds like you shoulda been using objects to bind data. Moo is one of the best OO toolkits out there. Can whip up really good long lived, testable, easy to understand stuff fast with extensive use of `lazy => 1`
Re:Pattern matching accepted for Python by tyingq on Tuesday February 09, 2021 @06:09PM (#26083755)
Thought I'd try to balance out all the Perl hate in the sibling comments.

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.

Re:Pattern matching accepted for Python by autoexec on Tuesday February 09, 2021 @08:51PM (#26084945)
I'm glad I'm not the only one around still using and enjoying Perl. I'm just starting to play around in Python now with the plan to rewrite/replace a few older Perl scripts so while I may not get much use out of Perl going forward, it's been great for tasks like log file parsing and reporting.
Re:Pattern matching accepted for Python by 0xbadcafebee on Tuesday February 09, 2021 @05:28PM (#26083285)
This is the first time in the history of the internet that anyone has complained about too much documentation.
Re:Pattern matching accepted for Python by adamc on Tuesday February 09, 2021 @05:50PM (#26083568)
I programmed in Perl 5 for several years. Ugh. That language was hard to read, and some of the features (list vs. scalar context, for example) were awful. I have never wanted to write another Perl program. Capable, but painful to maintain.
Re:Pattern matching accepted for Python by make3 on Tuesday February 09, 2021 @04:25PM (#26082558)
I think this comment is super exaggerated. In my experience pretty much all features in Python 3 by far are really welcome. The only features you're usually not supposed to use are very obvious ones, inspect, metaclasses and nested comprehensions, which are super uncommon and feel like dark magic that you would obviously not want to use, or just shit ugly code in the case of nested comprehensions.
Re:Pattern matching accepted for Python by pmart123 on Tuesday February 09, 2021 @04:38PM (#26082675)
I agree with this up through Python 3.7. The recent updates though seem to be unnecessary or have obtuse syntax.
Re:Pattern matching accepted for Python by make3 on Thursday February 11, 2021 @12:08AM (#26098442)
do you have specific examples? honestly I was against the walrus operator but having played with it for just two seconds I think it's really great and that people are making a bigger deal than needed about this
Re:Pattern matching accepted for Python by enriquto on Tuesday February 09, 2021 @05:41PM (#26083440)
What's the problem with nested comprehensions? How else do you create bi-dimensional stuff?
Re:Pattern matching accepted for Python by magnusmundus on Tuesday February 09, 2021 @06:11PM (#26083771)
Not the same kind of nesting, is it?

  [[None for _y in range(y)] for _x in range(x)]
for two dimensions is fine, while

  [None for _x in range(x) for _y in range(y)]
(to create a flattened 2-dim list? excuse the dummy example) is just begging for later headache. Explicit looping is much more readable. Note the flipped order of expressions -- these two statements create the same iterators.

Not to mention, you can even reuse the name for extra evil:

  [i for i in range(2) for i in range(3)]
results in

  [0, 1, 2, 0, 1, 2]
Re:Pattern matching accepted for Python by joshuamorton on Tuesday February 09, 2021 @06:41PM (#26084055)
Fwiw, I find creating a 2d array and then flattening (`itertools.chain.from_iterable([[None for _y in range(y)] for _x in range(x)])` to be both readable and reasonably concise, though yes explicit loops are also fine.
Re:Pattern matching accepted for Python by cat199 on Tuesday February 09, 2021 @11:21PM (#26085724)
nice trick.. though if you are relying on the 'generator' aspect of comprehensions this may be problematic (will create in-memory copies)
Re:Pattern matching accepted for Python by cjohnson318 on Tuesday February 09, 2021 @05:18PM (#26083148)
Yes, I think the general consensus on metaclasses is that if you don't already know what they are, then you probably don't need to use them. There's some metaclasses in Django, but it's pretty easy to see how you're expected to use them from examples, and you don't need to really understand what's going on.
Re:Pattern matching accepted for Python by whalesalad on Tuesday February 09, 2021 @04:13PM (#26082439)
String formatting with f"" has been the new sheriff in town for a while and it is really killer.
Re:Pattern matching accepted for Python by pletnes on Tuesday February 09, 2021 @04:28PM (#26082596)
Yes, and it also takes approx 11 seconds to learn, since str.format already had exactly the same syntax, just slightly more verbose.
Re:Pattern matching accepted for Python by leadingthenet on Tuesday February 09, 2021 @04:35PM (#26082647)
I never understood why they didn't remove the previous ones.

Isn't there supposed to be only one obvious way of doing these things?

Re:Pattern matching accepted for Python by contravariant on Tuesday February 09, 2021 @06:01PM (#26083670)
I would support removing the weird '%' operator, but str.format definitely still has uses. For one you can't make templates using f-strings since they are immediately evaluated.
Re:Pattern matching accepted for Python by notatoad on Tuesday February 09, 2021 @05:10PM (#26083067)
Python already broke backwards compatibility once. It didn't got over well
Re:Pattern matching accepted for Python by elisaado on Tuesday February 09, 2021 @04:37PM (#26082669)
You can't just remove things, that'd break stuff!
Re:Pattern matching accepted for Python by spockz on Tuesday February 09, 2021 @04:44PM (#26082731)
That is why scala has scalafix[1] where library maintainers can provide rules along with newer versions of libraries that can be used to automatically, either at build time or out of band on the source, translate old constructs/patterns in the new.

See it as deferred refactoring for library maintainers. Library maintainers that work in a monorepo with their users get this refactoring feature for free.

[1]: https://scalacenter.github.io/scalafix

Re:Pattern matching accepted for Python by lopatin on Tuesday February 09, 2021 @07:51PM (#26084556)
I have two thoughts on this: One is that tools like scalafix no-doubt rely heavily on static analysis to ensure correctness of their program transformations. I'm not sure a hypothetical "pythonfix" tool will be quite as feasible for untyped code bases.

And also, the issue isn't really with library maintainers when it comes to Python syntax changes. It's with all the user code written in Python. I tried converting my programs from Scala 2.12 from 2.13, and I failed so hard. I couldn't justify the time commitment, even with tools like scalafix to automate stuff. It's just not that smart.

All this is to say, let's not pretend that breaking changes to a programming language are ok. If you have to do break stuff once or twice in the lifetime of your language, fine. But accepting breaking changes as the status-quo is a failure of a language, by definition, IMO.

Re:Pattern matching accepted for Python by properdine on Tuesday February 09, 2021 @08:49PM (#26084939)
lib2to3 exists and is used by tools to do this kind of automatic refactoring for python. The idea of having a migration path to the "blessed" way to do things is pretty neat!
Re:Pattern matching accepted for Python by mahathu on Tuesday February 09, 2021 @07:06PM (#26084262)
As an occasional python developer - I remember you could use `from future import <function>` to use python3 features in python 2.x. perhaps it would be possible to introduce a `past` package to include deprecated language features? of course this would still break compatibility in some cases, but would make it much easier to update them
Re:Pattern matching accepted for Python by dragonwriter on Tuesday February 09, 2021 @08:53PM (#26084958)
> perhaps it would be possible to introduce a `past` package to include deprecated language features?

Deprecated language features are, by definition, still present and need no special incantation to miss, though they may produce Deprecation warnings to encourage you to update your code. Removed features would, I guess, be something you could do this for, except that generally the whole benefit of removing features is getting rid of the supporting code and the effort of maintaining it and it's interactions with new code.

Re:Pattern matching accepted for Python by leadingthenet on Tuesday February 09, 2021 @04:56PM (#26082893)
This is why the language is getting bloated. People shouldn't be so obstinately against breaking changes.
Re:Pattern matching accepted for Python by SubjectToChange on Tuesday February 09, 2021 @09:07PM (#26085026)
This is quite an alarming attitude that seems to be most common among the Python community. It seems like the 2->3 transition filtered out devs who felt strongly about backwards compatibility and the remaining devs have relatively little patience for objections against breaking changes.

There is a huge benefit to keeping existing code working as it is. Both for businesses and the ecosystem. It benefits everyone if the language does everything it can to keep that intact.

Re:Pattern matching accepted for Python by heavyset_go on Tuesday February 09, 2021 @07:58PM (#26084610)
This is the same orange site that thinks the Python 2 to Python 3 breaking changes are still relevant and worth arguing about in 2021.
Re:Pattern matching accepted for Python by perrygeo on Tuesday February 09, 2021 @08:33PM (#26084842)
Yes, f-strings are now the obvious way to format strings _if_ the template is fixed (not variable at runtime) _and_ variables are defined in the current scope. There are many many cases where this does not apply: hence str.format is still required.
Re:Pattern matching accepted for Python by linkdd on Tuesday February 09, 2021 @04:40PM (#26082695)

  greeting = "hello {}"
  greet = partial(str.format, greeting)
  greet("world")
How would you pass a variable format string to f"" ?
Re:Pattern matching accepted for Python by eljost on Tuesday February 09, 2021 @04:53PM (#26082851)
You can use variables in the formats.

  >>> flt = 1.2345
  >>> two = 2
  >>> f"{flt:.{two}f}"
  '1.23'
Re:Pattern matching accepted for Python by thaumasiotes on Tuesday February 09, 2021 @04:58PM (#26082909)
That is the opposite of the problem being posed. The question is how you define `greet` using f-strings.
Re:Pattern matching accepted for Python by sumzup on Tuesday February 09, 2021 @05:43PM (#26083473)

  greet = lambda x: f"hello {x}"
Re:Pattern matching accepted for Python by sumzup on Tuesday February 09, 2021 @05:40PM (#26083431)

  greet = lambda x: f"hello {x}"
Re:Pattern matching accepted for Python by linkdd on Tuesday February 09, 2021 @06:10PM (#26083765)
What if "hello {x}" is not a static string but was read from somewhere else?

Surely this would not work:

  greeting = "hello {x}"
  greet = lambda x: f greeting
Re:Pattern matching accepted for Python by staticassertion on Tuesday February 09, 2021 @06:14PM (#26083802)
Something along the lines of...

    code = 'f"{input()} {x}"'

    lambda x: eval(code)
(Please don't do this)
Re:Pattern matching accepted for Python by staticassertion on Tuesday February 09, 2021 @11:36PM (#26085783)

    code = 'f"here it is {eval(input())}"'
    (lambda: eval(code))()
k, there we go
Re:Pattern matching accepted for Python by linkdd on Tuesday February 09, 2021 @06:16PM (#26083832)
Yes, I'll stick to using str.format :)
Re:Pattern matching accepted for Python by klyrs on Wednesday February 10, 2021 @01:33AM (#26086230)
That isn't the purpose for f-strings. You still have % and .format
Re:Pattern matching accepted for Python by AlphaSite on Tuesday February 09, 2021 @08:28PM (#26084809)
You can’t use f-strings for that.
Re:Pattern matching accepted for Python by linkdd on Tuesday February 09, 2021 @10:18PM (#26085399)
That was exactly my point.
Re:Pattern matching accepted for Python by nokko on Tuesday February 09, 2021 @05:11PM (#26083081)
I mean, if you're comfortable with `functools.partial`, lambdas are no great stretch:

  greet_fstring = partial(lambda _,s: f"hello {s}", greeting)
Re:Pattern matching accepted for Python by thaumasiotes on Tuesday February 09, 2021 @04:58PM (#26082915)
Why is the example

  greet = partial(str.format, greeting)
  greet("world")
as opposed to just

  greeting.format("world")

?
Re:Pattern matching accepted for Python by contravariant on Tuesday February 09, 2021 @06:02PM (#26083678)
The real question is why they didn't just write:

    greet = greeting.format
Re:Pattern matching accepted for Python by linkdd on Tuesday February 09, 2021 @06:15PM (#26083817)
It was implying you could use the str.format function as argument to other computations, something you cannot do with f-strings.
Re:Pattern matching accepted for Python by pletnes on Tuesday February 09, 2021 @04:47PM (#26082784)
Or read the string to be formatted from a file, to name another use case.
Re:Pattern matching accepted for Python by agumonkey on Tuesday February 09, 2021 @05:37PM (#26083388)
I believe it's been a cause of care for very easy and expressive string formatting syntax in other languages
Re:Pattern matching accepted for Python by cjohnson318 on Tuesday February 09, 2021 @05:28PM (#26083282)
I think str.format() was an improvement on from % formatting, and that the f strings are an improvement on str.format(). It's readable, concise, and it's familiar from other scripting languages.

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.

Re:Pattern matching accepted for Python by oconnor663 on Tuesday February 09, 2021 @07:50PM (#26084554)
This argument is totally valid, but I think the problem is that it's universal. It seems like it's equally valid as an argument against any feature. So to really apply it in practice, we need to go further, and come up with some way to quantify the value a new feature brings, so that we can compare that value to the downside of more bloat.
Re:Pattern matching accepted for Python by 0xbadcafebee on Tuesday February 09, 2021 @05:43PM (#26083462)
If developers actually knew what simplicity was they'd stop worshipping it.

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.

Re:Pattern matching accepted for Python by chriswarbo on Tuesday February 09, 2021 @06:15PM (#26083827)
I regularly read cutting edge research papers whose code examples are expressed in lambda calculus, a language from the 1930s with 3 syntax rules and 1 reduction rule.
Re:Pattern matching accepted for Python by visarga on Tuesday February 09, 2021 @11:12PM (#26085667)
Not a powerful argument because in 90 years it's still not mainstream and only exists in papers and blog posts. On the other hand pattern matching is widely used. 'Simple' can be 'complicated' in another way, otherwise we'd prefer to write machine code.
Re:Pattern matching accepted for Python by pizza on Tuesday February 09, 2021 @04:13PM (#26082448)
This feature could make a lot of code that people write quite often a fair amount simpler, though. I'm looking forward to this feature quite a bit.
Re:Pattern matching accepted for Python by 01100011 on Tuesday February 09, 2021 @05:14PM (#26083114)
Maybe the problem with C++ is that it tries too hard to preserve backwards compatibility? I think it makes some of the newer features clunkier. If the C++ standards folks did something like Google's Abseil and provided an upgrade tool while discontinuing old features they might have ended up with a better language. I understand something like that might not work for everyone, but from what I've gathered in talking to other devs, there is a strong distaste for the current state of C++.
Re:Pattern matching accepted for Python by Kototama on Tuesday February 09, 2021 @07:27PM (#26084399)
> Maybe the problem with C++ is that it tries too hard to preserve backwards compatibility?

That's a funny one. The whole history of C++ is being backward compatible, originally with C.

Re:Pattern matching accepted for Python by superbcarrot on Tuesday February 09, 2021 @04:09PM (#26082412)
It's difficult to balance it out correctly. F-strings were a significant improvement and I still think it was a great idea to include them and trade off some of the language simplicty for the added convenience. This new pattern matching... I'm not convinced yet.
Re:Pattern matching accepted for Python by roelschroeven on Tuesday February 09, 2021 @04:26PM (#26082575)
Personally I don't feel f-strings are an improvement at all, but I think I can see why people prefer them. But a significant improvement, that I don't see at all. Can someone explain why e.g.

    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.
Re:Pattern matching accepted for Python by superbcarrot on Tuesday February 09, 2021 @04:32PM (#26082629)
I find the f-string version better because I read from left to right and find it unnatural when my eyes need to jump around several times over the same expression in order to parse it. In your example that effect isn't too strong because there isn't a lot of additional text in the string and it's very clear what's going on either way.
Re:Pattern matching accepted for Python by contravariant on Tuesday February 09, 2021 @06:19PM (#26083861)
Sometimes you just want to quote something in a string real quick. In some cases you want to do something slightly more complicated.

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.
Re:Pattern matching accepted for Python by cjohnson318 on Tuesday February 09, 2021 @05:33PM (#26083344)
Once you get over five arguments in str.format(), it gets weird. I reverse engineered a product that required a lot of string formatting, and f strings made things more readable and debuggable.
Re:Pattern matching accepted for Python by marcinzm on Tuesday February 09, 2021 @08:38PM (#26084871)
As I see it the less cognitive overhead I have when reading code the better. The more I have to think about the code I am reading the more likely I am to make a mistake because my brain is not a machine. With f" I simply read the code left and right and understand the output as I go. When I see the output I'm interested in I stop and see the context instantly. With .format() I read left and right, stop once I get to what I'm interested in, go back to count the {}s, remember the count, and finally count the arguments. Multiple places to make a mistake. And doing this when refactoring code is how you get bugs.
Re:Pattern matching accepted for Python by IanCal on Tuesday February 09, 2021 @04:34PM (#26082646)
> 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.

It makes it harder to see which values actually go where though. I really dislike the separation.

Re:Pattern matching accepted for Python by roelschroeven on Tuesday February 09, 2021 @04:49PM (#26082805)
> I really dislike the separation.

That's obviously a pretty fundamental difference in point-of-view. And it looks like your point-of-view is shared by a large majority.

"The reasonable man adapts himself to the world. The unreasonable man persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man." -- George Bernard Shaw

I try to be reasonable, so I guess I should try to come to terms with f-strings. In any case please don't depend on more progress.

Re:Pattern matching accepted for Python by thaumasiotes on Tuesday February 09, 2021 @05:02PM (#26082963)
> It makes it harder to see which values actually go where though.

You can name the variables in the format string and then pass the expressions as keyword parameters.

Re:Pattern matching accepted for Python by aidos on Tuesday February 09, 2021 @07:06PM (#26084259)
You can do that with f-strings too... but you don't need to because they're generally already clearer.
Re:Pattern matching accepted for Python by ju_sh on Tuesday February 09, 2021 @04:41PM (#26082709)
Thank goodness we still have both ;)
Re:Pattern matching accepted for Python by scarygliders on Tuesday February 09, 2021 @08:40PM (#26084893)
Thank you!

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

Re:Pattern matching accepted for Python by nuclear_eclipse on Tuesday February 09, 2021 @06:10PM (#26083760)
Just wait until you get Python 3.9 and can do:

    >>> a, b = 2, 4
    >>> f"{math.gcd(a, b) = }"
    'math.gcd(a, b) = 2'
Re:Pattern matching accepted for Python by mixmastamyk on Tuesday February 09, 2021 @07:02PM (#26084231)
The first is more readable and performant, the second is much more error prone. One of the things folks complain about in Python is runtime errors, this is one part of the solution.

Is that enough?

Re:Pattern matching accepted for Python by roelschroeven on Tuesday February 09, 2021 @08:47PM (#26084929)
I don't know about performant. If the difference is significant, that can be something to take into account, depending on the situation. Otherwise readability is more important.

So we come to readability, and I have to say that to me .format() is more readable. Honestly.

Regarding runtime errors, I presume you mean .format() doesn't prevent mismatches between the number of placeholders and the number of arguments, as in '{} {}'.format(42)? That's indeed a point in favor of f'', that I hadn't previously considered.

Re:Pattern matching accepted for Python by mixmastamyk on Tuesday February 09, 2021 @09:14PM (#26085061)
The eff string uses a special instruction that makes it not need to do expensive function lookups at runtime. These are costly in Python. Better in loops.

Readability is a win in my book. You mention too much is happening in your example string. Ok, perhaps it is. But remember, just because the interpolation supports expressions, doesn't mean you have to put them in there. I'd argue your function call would be better done on the line above, with only the result put in the string. This is the most readable version so far I think:

    c = math.gcd(a, b)
    f'gcd({a}, {b}) = {c}'
Syntax highlighting helps out as well.

Yes about placehoders. Also that in some cases of format() each variable is repeated a number of times:

    'hello {name}'.format(name=name)
When this is changed it is a bug magnet. DRY in a nutshell. Rarely is a feature a home run like this one. Not to mention I was using it in batch files, shells, and perl twenty-five years ago.
Re:Pattern matching accepted for Python by odonnellryan on Tuesday February 09, 2021 @08:05PM (#26084659)
I wouldn't say it is true with string formatting. I would tell a new dev to use the cool new syntax if I saw them using old syntax, but I don't think using the old syntax is painful at all to read.
Re:Pattern matching accepted for Python by nickysielicki on Tuesday February 09, 2021 @05:39PM (#26083409)
Already true with string formatting, map/filter versus comprehensions, plenty of other things.

Find me a modern language where that isn't true, though.

Re:Pattern matching accepted for Python by not_knuth on Tuesday February 09, 2021 @04:10PM (#26082417)
Obligatory Bjarne Stroustrup quote:

"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.

Re:Pattern matching accepted for Python by chriswarbo on Tuesday February 09, 2021 @06:14PM (#26083807)
> There are only two kinds of languages: the ones people complain about and the ones nobody uses.

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.

Re:Pattern matching accepted for Python by not_knuth on Wednesday February 10, 2021 @01:50AM (#26086294)
I also think using any quote as a thought terminating cliché is flawed. In that case I wouldn't blame the quote though, but the person using it. (I assume your boss probably had an interest in terminating thought. Perhaps the project was invested in the language and it was just not feasible to change? Perhaps he didn't have an answer to your valid criticism? Just speculation...)

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."

Re:Pattern matching accepted for Python by cat199 on Tuesday February 09, 2021 @11:29PM (#26085756)
> It's a rather useless form of binary thinking, since it completely ignores scale and severity.

You may also be interested in: "there are 10 kinds of people - those who understand binary, and those who do not"

Re:Pattern matching accepted for Python by neysofu on Tuesday February 09, 2021 @04:15PM (#26082469)
That quote is seriously overused, to the point where valid criticisms will be met with disapproval simply because the language falls under condition (1).
Re:Pattern matching accepted for Python by rrdharan on Tuesday February 09, 2021 @06:58PM (#26084203)
There are quotations people complain about and ones that no one recognizes.
Re:Pattern matching accepted for Python by im3w1l on Tuesday February 09, 2021 @06:57PM (#26084191)
The issue was not the breaking changes, the issue was that it was done poorly. In particular that v2 and v3 code could not coexist in the same project.
Re:Pattern matching accepted for Python by nostrademons on Tuesday February 09, 2021 @08:47PM (#26084928)
I think that they did it about as well as they could given the driving motivation behind the change. The semantics of existing syntax changed with Python 3: 'foo' is a string of ascii bytes in Python2, but a string of unicode characters in Python3. Treating a string as both ASCII and Unicode within the same project, depending on which codebase it originated in, seems like a recipe for disaster.

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.

Re:Pattern matching accepted for Python by gonzo41 on Tuesday February 09, 2021 @08:30PM (#26084821)
Come on down to golang town. Though I worry when the introduce generics things will spiral out of control.
Re:Pattern matching accepted for Python by pansa2 on Tuesday February 09, 2021 @08:37PM (#26084868)
Go has a different kind of complexity from Python, though. It makes you deal with low-level details like pointers and casting between different-sized integers, none of which are necessary in Python.
Re:Pattern matching accepted for Python by adamc on Tuesday February 09, 2021 @05:46PM (#26083514)
I don't really agree. I helped steer my organization to Python more than a decade ago -- its mix of capability and readability made it a great fit, and it remains so. Nothing I saw in this made me worried that people would struggle to read it. F-strings are great, a huge improvement on needing to say .format() all the time, and format was an improvement on the original use of % (more descriptive).

C++ is a wholly different beast. Template metaprogramming achieves great things, but at significant cost to readability.

Re:Pattern matching accepted for Python by geofft on Tuesday February 09, 2021 @07:23PM (#26084376)
That's been true for a very long while - in Python 2.1 (released just shy of 20 years ago), they added "new-style classes", class Foo(object), and for the entire life of Python 2 you weren't supposed to use "old-style classes", class Foo, because they behaved in confusing ways.

(Python 3 got rid of old-style classes and made the two syntaxes equivalent.)

Re:Pattern matching accepted for Python by 74d-fe6-2c6 on Tuesday February 09, 2021 @05:17PM (#26083142)
I need to justify six digits in Germany - we're not the Bay Area.
Re:Pattern matching accepted for Python by asah on Tuesday February 09, 2021 @05:30PM (#26083313)
sorry for the downvote: please propose solutions that allow the language to evolve and not stagnate.

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... )

Re:Pattern matching accepted for Python by chriswarbo on Tuesday February 09, 2021 @06:03PM (#26083691)
I wouldn't treat 'evolution' as an inherently good thing; i.e. change for its own sake.

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

Re:Pattern matching accepted for Python by lhjn on Tuesday February 09, 2021 @08:02PM (#26084638)
In scheme, or most other Lisps for that matter, you extend the language by writing a library, as the language extension tools are built-in and quite easy to use (macros). Very few other languages give you that kind of power, and certainly not python.
Re:Pattern matching accepted for Python by scatters on Tuesday February 09, 2021 @04:09PM (#26082410)
And packaging!
Re:Pattern matching accepted for Python by remram on Tuesday February 09, 2021 @06:09PM (#26083749)
This has been true for many, many years with "old-style classes".
Re:Pattern matching accepted for Python by _jjkk on Tuesday February 09, 2021 @04:06PM (#26082379)
I agree completely.

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...

Re:Pattern matching accepted for Python by atoav on Tuesday February 09, 2021 @04:26PM (#26082572)
Really? I program Python for over a decade now and compared to other language it was always the one where style somewhat was the smallest issue with that language (compared to the C, C++, C#, Javascript, Java I have seen).

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.

Re:Pattern matching accepted for Python by roelschroeven on Tuesday February 09, 2021 @04:31PM (#26082621)
I think grandparent is talking about something else. Large C++ codebases often have a guide that says which parts of the language to use and not to use. That can be useful if you have a team with people with different levels of expertise in the language, or expertise in different parts of the language. C++ has grown to be a language with a lot of different parts to choose from.

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.

Re:Pattern matching accepted for Python by atoav on Tuesday February 09, 2021 @04:46PM (#26082760)
Thanks for the clarification.
Re:Pattern matching accepted for Python by 533474 on Tuesday February 09, 2021 @04:54PM (#26082856)
grandparent?
Re:Pattern matching accepted for Python by roelschroeven on Tuesday February 09, 2021 @05:02PM (#26082961)
The parent comment of the parent of my comment, and by extension the writer of that comment.