List __iadd__, + = and return value

I noticed some strange behavior with return values ​​of list expansion.

I read this thread Why does + = behave unexpectedly in lists?

but that still doesn't make sense.

This is what I did:

Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul  2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1, 2]
>>> print(l.extend([1]))
None
>>> print(l.__iadd__([1]))
[1, 2, 1, 1]
>>> print(l += [1])
  File "<stdin>", line 1
print(l += [1])
         ^
SyntaxError: invalid syntax
>>> 

      

I understand that it extend

does not return an extended object as well None

. Not helpful, but I understand.

Now __iadd__

behaves differently, which is odd since I read that it is basically the calls to expand for the list.

But the third one puzzles me. I thought that +=

is the shorthand for __iadd__

, so why can I get SyntaxError

here? Moreover, it __iadd__

returns a modified list, which makes sense to pass as a return value. But I can't seem to use +=

(or *=

if that's the case, for example integers) in function calls.

Is it by design?

+3


source to share


2 answers


l.__iadd__(val)

is a function call, that is, an expression.

l += [1]

is an assignment, that is, an instruction.



The argument values ​​(the ones you provided in print

this case) cannot be operators, but only expressions as simple as this.

+1


source


__iadd__

used for implementation +=

, but they are not identical. l += [1]

is still an expression, but l.__iadd__([1])

an expression.



0


source







All Articles