New assignmens ...

Chris Angelico rosuav at gmail.com
Sat Oct 23 14:55:25 EDT 2021


On Sun, Oct 24, 2021 at 4:39 AM Jon Ribbens via Python-list
<python-list at python.org> wrote:
>
> On 2021-10-23, Chris Angelico <rosuav at gmail.com> wrote:
> > I've never used ctr:=ctr-1 either, though, so I don't know the actual
> > use cases. Why is this being used in an assignment expression? Is it
> > an ersatz loop?
> >
> > Common use-cases include:
> >
> > if m := re.match(...):
> >
> > while data := thing.read():
> >
> > etc. All of them are doing exactly two things: testing if something is
> > empty, and if it isn't, using it in a block of code.
> >
> > In what situations do you need to mutate an attribute and also test
> > it, and how much hassle is it to simply break it out into two lines?
>
> It's not hard to imagine something like:
>
>     def get_expensive(self):
>         return self.expensive or self.expensive := self.calculate_expensive()

I usually write this sort of thing the other way:

def get_expensive(self, key):
    if key not in self.cache:
        self.cache[key] = ...
    return self.cache[key]

and then if you don't like the duplication, the cleanest way is to put
the expensive calculation into the __missing__ method of a dict
subclass.

> > The onus is on you to show that it needs to be more flexible.
>
> Is it though? It seems to me that the onus is on you to show that
> this special case is special enough to be given its own unique
> existence. It's a bit surprising that the PEP doesn't discuss this
> decision at all.

The PEP was accepted. Thus it is now up to someone proposing a change
to show that the change is worthwhile.

Python has frequently started with a more restricted rule set, with
the option to make it less restricted in the future. Case in point:
Decorator syntax used to be limited to a small set of options, aimed
at the known use-cases at the time. Then very recently, that was
opened up to basically any expression.

https://www.python.org/dev/peps/pep-0614/

Read over that document for an excellent example of how to take a
tight proposal and recommend that it be made more flexible. Assignment
expressions are currently in the restricted form, allowing only simple
names, and it's up to you to propose and demonstrate the value of the
increased flexibility.

ChrisA


More information about the Python-list mailing list