[Python-ideas] Alternative spelling for list.append()

Michael Selik mike at selik.org
Mon Jun 18 22:14:41 EDT 2018


On Mon, Jun 18, 2018 at 6:20 PM Juancarlo Añez <apalala at gmail.com> wrote:

> For all practical purpose, it would be enough to define that the
>>> expression:
>>>
>>> mylist += [item]
>>>
>>> gets optimized to mylist.append(item).
>>>
>>
>> Unfortunately, that would create yet another special case of operators
>> breaking the rules. Most operators invoke magic methods. This would prevent
>> ``+=`` from invoking ``__iadd__`` for lists, since the right-hand side
>> would need to be compiled differently. It's similar to why ``and`` and
>> ``or`` keywords can't have magic methods.
>>
>
> It seems that the optimization is already in place:
>
>
> def main():
>     print(timeit.timeit('using_append()', globals=globals(), number=REPS))
>     print(timeit.timeit('using_concat()', globals=globals(), number=REPS))
>     print(timeit.timeit('using_iadd()', globals=globals(), number=REPS))
>
>
I'm not intimately familiar with the opcodes, but I believe that any code
involving the expression ``[x]`` will build a list.

In [2]: dis.dis("a += [x]")
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (x)
              4 BUILD_LIST               1
              6 INPLACE_ADD
              8 STORE_NAME               0 (a)
             10 LOAD_CONST               0 (None)
             12 RETURN_VALUE

I didn't run the timings, but I wouldn't be surprised if building a
one-element list is faster than looking up an attribute. Or vice-versa.

I thought you meant that you wanted to change the syntax such that ``a +=
[x]`` would, if the left-hand is a list, use different opcodes.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180618/649be207/attachment.html>


More information about the Python-ideas mailing list