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

Jonathan Fine jfine2358 at gmail.com
Fri Sep 28 04:55:07 EDT 2018


Summary: I recast an example in a more abstract form.

Steve D'Aprano wrote:
> Think about a more complex assignment:
>    text .= encode(spam) + str(eggs)

I find this example instructive. I hope the following is also instructive:

$ python3
>>> obj += incr
NameError: name 'obj' is not defined
>>> obj = object()
>>> obj += incr
NameError: name 'incr' is not defined
>>> incr = 1
>>> obj += incr
TypeError: unsupported operand type(s) for +=: 'object' and 'int'
>>> incr = object()
>>> obj += incr
TypeError: unsupported operand type(s) for +=: 'object' and 'object'
>>> obj +=  [] + ()
TypeError: can only concatenate list (not "tuple") to list

To me this shows that
    LHS += RHS
works as follows:

1. Evaluate the LHS (as an assignable object).
2. Evaluate the RHS (as a value).

and then some more steps, not covered in my example.

As syntax the compound symbols '+=' and '.=' are similar. But in
semantics, '+=' does and '.=' does not have an evaluation of the RHS
as an expression. This is, in abstract terms, the origin of Steve's
example. Someone else has noted that '+=' and its variants are focused
on numeric operations, such as addition.

This shows, to me, that the simplification provided by use cases such as
    text = text.replace("foo","bar")
has to be compared to the complexity introduced by
     text .= encode(spam) + str(eggs)

In other words, I've restated Steve's example, in a more abstract
form. I hope it helps to have another way to look at this example.

Finally, I note

>>> a = 2
>>> a **= 3
>>> a
8

-- 
Jonathan


More information about the Python-ideas mailing list