Hacker Newsnew | past | comments | ask | show | jobs | submit | oooooof's commentslogin

What is it? The link points to a discussion more deep than I’m willing to read.


Basically it's about adding := as an "assignment expression operator", that does assignment and returns the value as an expression. That is, take this regex example:

    match1 = re1.match(text)

    if match1 is not None:
        do_stuff()
    else:
        match2 = re2.match(text)

        if match2 is not None:
            do_other_stuff()
Which is a bit clunky. you only want to evaluate match2 in case match1 fails, but that means a new level of nesting. Instead, with this proposal, you could do this:

    if (match1 := re1.match(text)) is not None:
        do_stuff();
    elif (match2 := re2.match(text)) is not None:
        do_other_stuff()
Evaluate and assign in the if-statement itself. This is not dissimilar to the equals operator in C. In C, you would frequently find loops like `while ((c = read()) != EOF) { ... }`. This would presumably allow a similar pattern in python as well.

More information can be found in PEP-572: https://www.python.org/dev/peps/pep-0572/


Hehe. More chances for C-style bugs like:

if (a = b) /* Oooops, meant a == b! */


Presumably that's why they've gone with the far more sensible ":=" syntax.

The use of "=" for assignment has long been a pet peeve of mine. It was a mistake when C did it, and it's been a mistake for so many subsequent languages to copy it.

"=" shouldn't be an operator at all, it makes a lot more sense to use ":=" and "==".

Pascal's use of ":=" for assignment and "=" for equality, strikes me as almost as clear.

Still, at least C makes consistent use of '=' for assignment, unlike that god-forsaken trainwreck of a language, VB.Net, which uses it for both assignment and for equality depending on context.


It's not a problem in C anymore as modern compilers warn about that so you had to put additional parenthesis to make it clearer.

I like C way of assignment being an expression. I think having separate statement and then assignment expresdion is a mess. It's still useful though as Python was missing where keyword like feature from Haskell which is necessary to avoid duplicating computation in list comprehension.


Except it's more likely you're accidentally inserting a character twice than inserting another extra character (':')


Difference is bigger, C is `if (a = b)` vs `if (a == b)`. Python is `if (a := b)` vs `if a == b`


It's a controversial PEP https://www.python.org/dev/peps/pep-0572/ which allows you to write Python like this:

    def foo():
        if n := randint(0, 3):
            return n ** 2
        return 1337


    [(x, y, x/y) for x in input_data if (y := f(x)) > 0]


It also seems include a special case for if/while that lets you do:

    def foo():
        if randint(0, 3) as n:
            return n ** 2
        return 1337
which looks a bit better to me.


I think that's a rejected alternative proposal, not part of this PEP.



This is horrible. It looks like ":=" is a comparison operator. The last line is dangerously close to Erlang list comprehensions:

[ {X, Y, X/Y} || X <- Some_Function (), Y <- Some_Other_Function () ]

And people bitch about Erlang syntax.

Edit: "/" is the division operator


This immediately looks useful for things like:

    if foo := bar[baz]:
        bar[baz] += 1
        return foo
    else:
        bar[baz] = 1
        return 0
Where foo is a dict keeping track of multiple things, and a non-existing key (baz) is never an error but rather the start of a new count. Faster and more readable than

    if baz in list(bar.keys()):
    ....
Similar to Swift’s ‘if let’, it seems.


The place I see using it is in (quoting Python's "python.exe-gdb.py"):

        m = re.match(r'\s*(\d+)\s*', args)
        if m:
            start = int(m.group(0))
            end = start + 10

        m = re.match(r'\s*(\d+)\s*,\s*(\d+)\s*', args)
        if m:
            start, end = map(int, m.groups())
With the new syntax this becomes:

        if m := re.match(r'\s*(\d+)\s*', args):
            start = int(m.group(0))
            end = start + 10

        if m := re.match(r'\s*(\d+)\s*,\s*(\d+)\s*', args)
            start, end = map(int, m.groups())
This pattern occurs just often enough to be a nuisance. For another example drawn from the standard library, here's modified code from "platform.py"

    # Parse the first line
    if (m := _lsb_release_version.match(firstline)) is not None:
        # LSB format: "distro release x.x (codename)"
        return tuple(m.groups())

    # Pre-LSB format: "distro x.x (codename)"
    if (m := _release_version.match(firstline)) is not None:
        return tuple(m.groups())

    # Unknown format... take the first two words
    if l := firstline.strip().split():
        version = l[0]
        if len(l) > 1:
            id = l[1]


It' a problem with re module really.

re.match should return a match object no matter what, and .group() should return strings, empty string if non were matched.


I don't see how that would improve things. Could you sketch a solution based around your ideas?


Don't wait for 3.8, and don't bother with defaultdict.

collections.Counter is what you want for the counting case.

dict.get() + dict.setdefault() for the general case.

defaultdict is only useful if the factory is expensive to call.


As pointed, you can use either a default dict or just simply, and [more pythonic](https://blogs.msdn.microsoft.com/pythonengineering/2016/06/2...):

    try:
      bar[baz] += 1
    except KeyError:
      bar[baz] = 1
Also you can check if a key is in a dict simply by doing "if baz in bar" no need for "list(bar.keys())", which will be slow (temp object + linear scan) vs O(1) hashmap lookup.


The error-catching method seemed too drastic to me before, but the article explains the LBYL vs. EAFP arugument quite well. Thanks!

I should find a way to get more code reviews, I really enjoy learning these small nuggets of info.


Alternatively

`bar[baz] = bar.get(baz, 0) + 1`

One line and no error checking.

But the OP was probably just illustrating a basic example where you might have some more intense logic


It's also time saving since the hash lookup needs to be done at most 1, as well. GP has two lookups in the hash list.


For stuff like that I'd just use `defaultdict`. That if/else tree then reduces to 2 lines total.


That’s a good tip, thanks!


Would've making regular assignment an expression broken too much existing code?


It's a voluntary design choice since the beginning of Python to avoid the very common mistake of doing:

    while continue = "yes":
instead of:

    while continue == "yes":
Those mistakes introduce bugs that are hard to spot because they don't cause an immediate error, linters can hardly help with them and even a senior can make them while being tired.


I don't know about linters but GCC warns me about that every time I make that typo. They could just require parenthesis when assignment value is used as boolean.


Probably not, since expressions can already be statements. But that would allow dangerous code like "if a = 3", which I don't think the Python devs would want to allow.


Reminds me of the kind of hacks you would find in an old-school K&R book.


Can somebody comment on why is this PEP controversial?


I don't think the controversy here is with the feature itself, more with the implementation. Many, me included, would have preferred to seen a different implementation of solutions to the same problems.

Code starts becoming a lot harder to reason about when more than one state is mutated on the same line. The good design of Python makes this harder than in say C and I think this is a step in the wrong direction in that regard.

The two real things this solves are checking for truthyness in an if and reusing values in a filterting comprehension. Instead of the syntax we have now that can be used anywhere, adds a whole new concept and feels kind of out-of-place, I would have much preferred a solution that can only be used in vetted places, doesn't add a new thing people need to learn and follows the style of the language

For example, my preferred solution for `if` would have been:

    if thing() as t:
        print(t)
Usage of `as` is already established by the `with` block

    [value for x in y
     if value
     where value = x * 2]
The order is unfortunately a bit weird here, but there is no need to add the whole concept of a different type of assignment and this syntax will feel instantly recognizable to people familiar mathematical notation, which is where the existing list comprehension syntax comes from and so has been established as well.


I wanted "as" too. But the accepted operator has the benefit of integrating perfectly with type hints.


For many people (including me) who learned Python the way that, in languages like C, the `if x=2` assignment combined with condition is an anti-pattern and prone to errors.

This PEP solves very little problem, saves a few characters of code, but adds complexity to readability.


It makes list expressions and some other things more powerful, but some feel the potential to create difficult-to-understand constructs with it is too high and the current ways of writing such code are clear enough.


Ick.


I've come around to it purely based on the application in list comprehensions.


The proposal: https://www.python.org/dev/peps/pep-0572/

Short version.

(x =: y) is an expression that:

1. assigns the value y to the variable x

2. has the value y.

So `print((x := 1) + 1)` prints '2', and sets x=1.

A ton of languages [eg: c, js] have '=' work this way. And a ton of style guides for those languages tell you to avoid using it like that, because it's confusing. So this is a bit controversial.


You're allowed to do assignments inside of expressions

E.g.

    if(x:=f() is not None):
        print(x)
You can read more about it here: https://www.python.org/dev/peps/pep-0572/


I'm immediately skeptical after seeing this example because I'm not sure if the first line parses as:

  if (x := f()) is not None:
or as:

  if x := (f() is not None):


That's why parenthesis are mandatory.


:= overrules everything except a comma, so it's the latter. Still, I agree it's potentially confusing.


High-level overview: it's an assignment operator that returns its value, similar to C's assignment operator.

The choice of := is to avoid accidentally using assignment where comparison is expected.


I feel the colon is unnecessary, especially considering how C deals with this. A plain '=' inside a conditional is already invalid syntax in Python.


And it's a very well-known source of bugs in C, since it's to close to "==". I don't think new languages adopting that is a good idea.


Sure. But if fidelity to C style was not a concern then I don't see why the '==' syntax was adopted in the first place.


== is an incredibly common syntax for equality and stand-alone not a problem. only if you introduce = to expressions too it becomes a risk. (well, you could theoretically accidentally write == for a normal assignment, but that kind of error is caught more easily)


No, it's necessary.


How so? Syntactically, or from a pragmatic point of view?


Yeah but there is already solution for that in C: put parenthesis around assignment when using its value as bool. The compilers warn if you don't so making this error in C can only happen if you don't use warnings.



Wow if that’s possible on google cloud then I agree wholeheartedly.... don’t risk your business by using google cloud.


Or indeed why any sentient alien should care.

“Apes became conscious, heated up and destroyed their environment, forced back to wilderness, evolved out. Meh... who cares.”


The idea that humanity will ever travel even to the nearest star is pure fiction.

Anyone who thinks otherwise just fails to grasp the distances involved. They are so large as to be beyond understanding.


The idea that humanity won't ever travel even to the nearest star is pure fiction.

Anyone who thinks otherwise just fails to grasp exponential growth. They are so large as to be beyond understanding.


"...won't ever... is pure fiction"

Do you mean to say humanity certainly could travel to the nearest star?

I'm skeptical that anything resembling humanity could because everlasting exponential growth requires infinite resources. And humanity evolved on an abundant--but far from infinite--gravity well.


I was mostly making a point that grandiose statements can be rebutted by similar (in this case, changing 3 words) grandiose statements.

To answer your question though, the main problem with space travel isn't physics (assuming you are ok with long travel times), it's economics. We have sent astronauts to the moon and probes all across the solar system. The main reason we don't do more though is because of how expensive it is. However, a thousand years of 2% growth (not a given but again, grandiose) means we would have 400 million times more money to possibly spend on space travel. A NASA budget 400 million times larger could certainly build and send a spaceship 4 light years to alpha centauri.

Now how long will we sustain exponential growth? Well that's anyones guess but I don't see us becoming resource constrained for a long long time. The sun produces 10^13 more energy than the world used in 2013 according to [0] and we have plenty of resources in the solar system to build with (and we can recycle more).

[0]: https://www.quora.com/How-much-energy-does-the-sun-produce-p...


> To answer your question though, the main problem with space travel isn't physics (assuming you are ok with long travel times), it's economics.

I'd argue it's biology, not physics. Sending a rock to another star is easy. Sending a rock that can send back data is probably possible with our technology, but it's unlikely it would retain data transmission capabilities long enough to actually report back from another star. Sending a bunch of humans and keeping them alive the entire journey? It's not clear we can do that for a round trip to Mars, let alone an interstellar journey.


The 2 biggest health problems that I am aware of with spaceflight are due to weightlessness and radiation. However, both can be probably be solved with enough money (make the spaceship a rotating one with artificial gravity and add more shielding). There might be others but I am pretty confident you could engineer your way past each and every one given a large enough budget.


You're sort of missing the biggest health problem of all: how do you make a self-sustaining closed ecosystem?


True, I was thinking more in the context of the mars trip you mentioned where you can generally take the resources you need for the trip. For intersteller travel, you would need to make it self sustaining since the travel times are so long and that would be extremely expensive.


The article suggests moving stars.


Let's be a bit more positive on Humanity's progress eh?

Humanity is on the cusp of three major technological breakthroughs that will quite literally change everything.

1) AI. Even if we don't reach ASI in the near term, we'll have ANI to help us research new technologies in months/years rather than decades.

2) Asteroid Mining. Whether it's Musk/Bezos/A. N. Other, the very first time someone brings down an asteroid. It will herald the dawn of abundance for precious metals. What will happen to prices is another topic. But this will allow researchers to develop even more exotic materials.

With better materials resistant to heat, more conductive elements, etc, etc. Humanity be able to build what can only be dreamt of.

3) 7 Billion (now). 13 Billion with Mars, 50+ Billion with Europa, Titan, Ganymede, etc, etc, etc. There will be a time where Humans will stretch beyond this solar system. Imagine how many breakthroughs will be possible with 100m researchers and AI trying to crack something?

What will make this possible? With 1 and 2, we'll be able to finally crack fusion reactors. This will enable faster space travel than with current engines. Habitats will evolve from those initial Mars missions and will sprawl into mega cities. Who knows, there may even be Luxury apartments hovering in the upper atmosphere of Venus.

All this progress is exponential and if you stop to look around. The seeds are being sewn right now. By 2050, some things we consider Sci-fi will be reality.

Oh and I'll just throw this one in.

4) Nasa has been doing some work on the Alcubierre drive. Who is to say, that the issues that cannot be surmounted now, will be in the future? For those that want to know more. I'll leave a channel that goes into such things [0].

[0]: https://www.youtube.com/channel/UC2kkCGRqZWaSIK3BmLC8vaw/vid...


> 2) Asteroid Mining. Whether it's Musk/Bezos/A. N. Other, the very first time someone brings down an asteroid. It will herald the dawn of abundance for precious metals. What will happen to prices is another topic. But this will allow researchers to develop even more exotic materials.

Say what? The idea that asteroid mining will enable material science revolutions is fanciful. We're not exactly short on metals (even precious metals). And interplanetary space is less extreme than environments we can create in terrestrial situations, so we're not going to find weird new stuff by poking around asteroids.


>We're not exactly short on metals (even precious metals).

Last I checked, the price of most metals was greater than zero. They're commodity markets, so that means they're scarce. If you mean "available at any price," then we were not short on iron during the Bronze age or short on Aluminum during the early 1800s.


Well, it is possible that if rare and expensive metals become dirt cheap, new exotic alloys may be developed that were previously economically inconceivable.

I don't know how likely this is. I imagine plenty of research has already been done on exotic alloys, however I wonder how much that research has been affected by economic constraints.


Alcubierre drives require exotic matter which is not quite ruled out by the laws of physics. Hopefully they don't require Jupiter-sized masses of the stuff, although some have suggested as much. However, that solved, there are two slight problems with this idea. One is that FTL inherently violates causality, which is sort of a problem. The other is that the spacecraft is expected to pick up and accelerate with it basically any matter it runs into along its superluminal path, releasing these as a spectacular shower of near-c particles whenever it stops. Your other speculations have their own defects, but I'll let others address them.


The distance to the moon is already beyond intuition, but you can still understand how to get there by doing calculations. If the numbers say that it's possible then it's possible.


My vote is still with the brain in a jar (or something close to it). Fewer resources, less area, and much of the life support equipment could be shared between many individuals. There's reason to believe it would extend lifespans as well, provided that an entirely virtual life could be made worth living.

I honestly think we'll achieve this long before we're able to properly or effectively simulate a brain with computers of any kind.


the _nearest_ star is actually quiet close :-]


thats pretty accurate as far as current technology goes, but then again with a few additional centuries of research we never know what we end up achieving.


We could just about do interstellar now if an existential threat called for it. Project Orion or a nuclear salt water rocket are both possible already.


Errr. I think by 2400 we’ve got every chance of living in the ruins of a past grand human civilization.

Trillion is nice sci fi. 10,000 years in the future with any recognizable civilization is even more of a stretch.


A stretch indeed but interesting to think about nonetheless:

10,000 years in the future is the premise of Frank Herbert‘s Dune.

The novel (or rather the series) depicts a mankind that on one hand in some ways has evolved way beyond humanity’s current capabilities.

On the other hand, society has devolved into a feudal state.

Some technologies are shunned and outlawed for their destructive potential, most notably nuclear weapons and “thinking machines” (there’s some room for interpretation if this just means AI or computers in general), which have been replaced by “mentats” (basically human computers).


400 years is nothing. I mean, climate change is real and could be very damaging, but what aside from that and war - why do you think we’ll be living amongst ruins? That seems overly pessimistic to me.


Water is already running out in many areas of the world. Rains are failing worldwide.

No water = no food. Where millions perhaps billions of people are on the move, societies will break down. Look what is happening on the European and US borders and the hysteria it generates when the migration is but a trickle of what is to come.

Yes humanity and technology is moving forward at record speeds, but at what cost to the world majority? To the environment.

I think by 2400 is a rather optimistic figure, it is likely to be much sooner


Fresh water is running out. If you have enough cheap energy, desalination solves that problem.


400 years is enough time for us to nuke ourselves out of being able to sustain our society, and climate change is a classic cause of wars.


30 years ago there was a very real prospect of a Worldwide nuclear war -- my mother was, in the UK, involved in creation of shelters to allow some kernel to survive the ensuing nuclear winter. Apocalyptic films were portending doom and in school we watched films about what to do if there was a nuclear blast.

There have been massive wars/killings, massive famines, massive epidemics.

We're in what may well be a local maxima, or perhaps an overall maxima. There are a lot of challenges to face that we need to unify to fight, like water poverty, food security, avoiding escalation of conflict - and not much sign of greater unification (quite the opposite AFAICT).

IMO we can turn it around, but we're going to have to have a sudden outbreak of altruism.


> water poverty, food security, avoiding escalation of conflict

Two out of three of those problems are getting easier with technology (renewable energy for desalination and smart agriculture). If we leave this maxima, it will be because we permitted nuclear proliferation. Even that isn’t inescapable, however.


Thats a pretty pessimistic view to have when we live in an era of ongoing progress in almost every area.


A pessimistic or at least skeptical dialectic counterpart to the optimistic/progressive worldview is a valuable thing to have, I think.

You can't reach into people's brains and change their temperament (yet! say the optimists) but I don't think we should want to. And not allpessimism/skepticism is based on temperament, though certainly some is.


That's a very anthropocentric view. We have a single point of failure. It's not likely to drastically change in any reasonable time-frame.



Speaking of pessimism, i just hope we humans destroy each other before we destroy earth to pave way to species which is not so hell bent on personal over society.


I don't get it. I mean this is the premise of many sci-fi stories, but humanity has made pretty steady civilized progress since its inferred inception. There isn't much of a reason to believe this pessimism.


Prior civilizations collapsed after over-exploiting their environment, and we're making the same mistake on a global scale. Our complex supply chains based on fossil fuels are rather fragile - we will likely survive a collapse at reduced quality of a life, however total recovery may be slow or impossible depending on remaining resources.


We can produce more food than ever with less energy. Knowledge transfer is always improving, and with computer programs it will be even easier to transfer knowledge.

You guys need to clarify what "a collapse" is. Not eating as much meat? Do you really think that we would not be able to power our computers or not be able to produce rice/wheat on any industrial scale?

The amount of FUD spread without any foundation for it is maddening.


> We can produce more food than ever with less energy. Knowledge transfer is always improving...

I imagine that's what people said before the Dark Ages too. It's not as if empires and civilizations haven't ever fallen before.


Yes, but civilizations and empires are not representative of the progress of humanity as a whole. Besides, isn't Dark Ages a rejected term by historians now? In addition, what is 200-400 years in the history of civilization? Of course there will be volatility - just like life on an individual level, the stock market, annual crop yields, etc.


An abrupt, significant, and wide-spread regression in quality of life, coupled with cultural and technological stagnation. Something like the Late Bronze age collapse ( https://en.wikipedia.org/wiki/Late_Bronze_Age_collapse )

It is a reasonable low-probability high-risk concern, given (unordered):

* Depleting fossil fuel reserves: most obvious risk; dominant fuel source for transportation and agriculture, dominant energy source for industries, dominant material in many consumer goods.

* Climate change: threatens some regions' agricultural and ocean productivity, pressuring human migration, spreading diseases.

* Exhausted oceans: oceanic deadzones are spreading, loss of fishing as a food source is a serious risk for parts of Asia, which will put additional pressures on agriculture and motivate economic migration.

* Over-use of antibiotics and vaccines: risk of super-bacteria/virus plagues, mostly in agriculture and 3rd world nations.

* Depletion of aquifers: imminent risk amplified by climate change. America's food production is heavily reliant on effectively non-renewable aquifers, depletion or poisoning through fracking are serious risks.

* Globalized economy/supply chains: coupling economies improves efficiency but introduces the risk of cascade failures.

No one of these problems are an existential risk by themselves... but they are all interrelated and poorly understood, which impacts our ability to effectively preempt wide-spread impact.

Humanity will recover should the worst happen, but I think it's better to avoid the set back in the first place.


Have you met humans?


Errr.... hold on ... I can build every component of a complete system, front end, back end, deployment, database.

Maybe I don’t exist.


I paid everyone back who was financially out by working and saving for many years.


That means that Trump is the most powerful person in the universe.


For relationship success you must both also be effective at communicating with each other, able to talk openly.

You also need to be able to discuss challenges and issues without eroding the value of the relationship.


If you mean SMS, it’s not secure.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: