New assignmens ...

Chris Angelico rosuav at gmail.com
Fri Oct 22 21:41:55 EDT 2021


On Sat, Oct 23, 2021 at 12:24 PM Paulo da Silva
<p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt> wrote:
>
> Às 20:34 de 22/10/21, Chris Angelico escreveu:
> > On Sat, Oct 23, 2021 at 6:24 AM Jon Ribbens via Python-list
> > <python-list at python.org> wrote:
> >>
> >> On 2021-10-22, Stefan Ram <ram at zedat.fu-berlin.de> wrote:
> >>> Paulo da Silva <p_d_a_s_i_l_v_a_ns at nonetnoaddress.pt> writes:
> >>>> Why doesn't this work
> >>>>      if (self.ctr:=self.ctr-1)<=0:
> >>>> while this works
> >>>>      if (ctr:=ctr-1)<=0:
> >>>
> >>>   assignment_expression ::=  [identifier ":="] expression,
> >>>   but the attribute references "self.ctr" is no identifier!
> >>
> >> This seems a surprising omission. You'd expect at least 'attributeref'
> >> and 'subscription' to be allowed, if not the whole of 'target'.
> >
> > That's not the primary use-case for assignment expressions, and they
> > were highly controversial. It is much easier to expand it afterwards
> > than to restrict it, or to have the feature rejected because people
> > are scared of some small aspect of it.
> >
> > If you want to propose relaxing the restrictions, make your use-case
> > and attempt to convince people of the value.
> >
> Well, I didn't follow the discussion of this new feature, but the reason
> I can see behind allowing it seems so valid for for ctr:=ctr-1 as for
> self.ctr:=self.ctr-1. The kind of use is exactly the same. One is for a
> normal function, the other for a method.
> IMHO this makes no sense at all. Arguable may be for example LHS
> ctrs[i], or something like that. But self.ctr ...! Too weird.
>

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?
The onus is on you to show that it needs to be more flexible.

ChrisA


More information about the Python-list mailing list