[Python-ideas] Add .= as a method return value assignment operator

Anders Hovmöller boxed at killingar.net
Fri Sep 28 06:42:04 EDT 2018



>>> Think about a more complex assignment:
>>> 
>>>   text .= encode(spam) + str(eggs)
>> 
>> I think the only sane thing would be to disallow that, and
>> require the RHS to have the form of a function call, which is
>> always interpreted as a method of the LHS.
> 
> 
> You obviously have a different idea of what is "sane" than I do :-)
> 
> But okay, so we cripple the RHS so that it can only be a single method 
> call. So useful things like these are out:
> 
>    target .= method(arg) or default
> 
>    target .= foo(arg) if condition else bar(arg)
> 
> and even 
> 
>    target .= method(args) + 1
> 
> making the syntax pure sugar for
> 
>    target = target.method(args)
> 
> and absolutely nothing else. I think that's the sort of thing which 
> gives syntactic sugar a bad name.
> 
> The one positive I can see is that if the target is a compound 
> expression, it could be evaluated once only:
> 
>    spam[0](x, y, z).eggs['cheese'].aardvark .= method(args)
> 
> I suppose if I wrote a lot of code like that, aside from (probably?)
> violating the Law of Demeter, I might like this syntax because it 
> avoids repeating a long compound target.

I don’t really like this proposal for the same reasons you do I think but let’s play devils advocate for a while... I would then suggest something more readable like:

foo as x = x.bar or x.something_else or even_another_thing

This avoids the iffy hanging dot while allowing more complex and readable statements. It also expands trivially to tuple unpacking which the .= syntax does not.

/ Anders


More information about the Python-ideas mailing list