asottile / pyupgrade

A tool (and pre-commit hook) to automatically upgrade syntax for newer versions of the language.
MIT License
3.5k stars 177 forks source link

What's the rationale for the rewrite of unpacked list comprehensions #961

Open sk- opened 1 month ago

sk- commented 1 month ago

The rule rewriting unpacked list comprehensions does not seem to have been properly justified in either the PR or the original issue.

In my local testing list comprehension unpacking is ~3x faster than the generator code, so why is unpacking a generator the preferred modern way?

System Python 3.12.4 (main, Jun 6 2024, 18:26:44) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin Mac OS Sonoma 14.5

$ python -m timeit "a,b = [i for i in range(2)]"
5000000 loops, best of 5: 78.3 nsec per loop
$ python -m timeit "a,b,c = [i for i in range(3)]"
5000000 loops, best of 5: 86.2 nsec per loop
$ python -m timeit "a,b,c,d = [i for i in range(4)]"
5000000 loops, best of 5: 92.7 nsec per loop
$ python -m timeit "a,b,c,d,e = [i for i in range(5)]"
2000000 loops, best of 5: 114 nsec per loop

$ python -m timeit "a,b = (i for i in range(2))"
1000000 loops, best of 5: 225 nsec per loop
$ python -m timeit "a,b,c = (i for i in range(3))"
1000000 loops, best of 5: 263 nsec per loop
$python -m timeit "a,b,c,d = (i for i in range(4))"
1000000 loops, best of 5: 286 nsec per loop
$ python -m timeit "a,b,c,d,e = (i for i in range(5))"
1000000 loops, best of 5: 321 nsec per loop

cc @graingert as he requested the feature.