[issue42754] Unpacking of literals inside other literals should be optimised away by the compiler

Patrick Reader report at bugs.python.org
Sun Dec 27 02:56:34 EST 2020


New submission from Patrick Reader <pxeger at protonmail.com>:

When unpacking a collection or string literal inside another literal, the compiler should optimise the unpacking away and store the resultant collection simply as another constant tuple, so that `[*'123', '4', '5']` is the exact same as `['1', '2', '3', '4', '5']`.

Compare:

```
>>> dis.dis("[*'123', '4', '5']")
  1           0 BUILD_LIST               0
              2 BUILD_LIST               0
              4 LOAD_CONST               0 ('123')
              6 LIST_EXTEND              1
              8 LIST_EXTEND              1
             10 LOAD_CONST               1 ('4')
             12 LIST_APPEND              1
             14 LOAD_CONST               2 ('5')
             16 LIST_APPEND              1
```

vs.

```
>>> dis.dis("['1', '2', '3', '4', '5']")
  1           0 BUILD_LIST               0
              2 LOAD_CONST               0 (('1', '2', '3', '4', '5'))
              4 LIST_EXTEND              1
```

and `timeit` shows the latter to be over 3 times as fast.

For example, when generating a list of characters, it is easier and more readable to do `alphabet = [*"abcde"]` instead of `alphabet = ["a", "b", "c", "d", "e"]`. The programmer can do what is most obvious without worrying about performance, because the compiler can do it itself.

----------
components: Interpreter Core
messages: 383837
nosy: pxeger
priority: normal
severity: normal
status: open
title: Unpacking of literals inside other literals should be optimised away by the compiler

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42754>
_______________________________________


More information about the Python-bugs-list mailing list