bpo-32856: Optimize the assignment idiom in comprehensions. (GH-16814)
Now `for y in [expr]` in comprehensions is as fast as a simple
assignment `y = expr`.
diff --git a/Lib/test/test_peepholer.py b/Lib/test/test_peepholer.py
index 567e6a1..7913e91 100644
--- a/Lib/test/test_peepholer.py
+++ b/Lib/test/test_peepholer.py
@@ -495,6 +495,20 @@
return 6
self.check_lnotab(f)
+ def test_assignment_idiom_in_comprehensions(self):
+ def listcomp():
+ return [y for x in a for y in [f(x)]]
+ self.assertEqual(count_instr_recursively(listcomp, 'FOR_ITER'), 1)
+ def setcomp():
+ return {y for x in a for y in [f(x)]}
+ self.assertEqual(count_instr_recursively(setcomp, 'FOR_ITER'), 1)
+ def dictcomp():
+ return {y: y for x in a for y in [f(x)]}
+ self.assertEqual(count_instr_recursively(dictcomp, 'FOR_ITER'), 1)
+ def genexpr():
+ return (y for x in a for y in [f(x)])
+ self.assertEqual(count_instr_recursively(genexpr, 'FOR_ITER'), 1)
+
class TestBuglets(unittest.TestCase):