Skip to content

Commit df9a967

Browse files
committed
Don't write to _ if it's never read
This is common in code like: ```python for _ in range(10): pass ```
1 parent 9da2000 commit df9a967

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

library/_compiler.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,21 @@ def visitBinOp(self, node: ast.BinOp) -> ast.expr:
211211
class PyroFlowGraph(PyFlowGraph38):
212212
opcode = opcodepyro.opcode
213213

214+
def optimizeStoreUnderscore(self):
215+
for block in self.getBlocksInOrder():
216+
for instr in block.getInstructions():
217+
if (
218+
instr.opname == "LOAD_FAST" or instr.opname == "DELETE_FAST"
219+
) and instr.oparg == "_":
220+
return
221+
# We never read from or delete _, so we can replace all stores to it
222+
# with POP_TOP.
223+
for block in self.getBlocksInOrder():
224+
for instr in block.getInstructions():
225+
if instr.opname == "STORE_FAST" and instr.oparg == "_":
226+
instr.opname = "POP_TOP"
227+
instr.oparg = None
228+
214229
def optimizeLoadFast(self):
215230
blocks = self.getBlocksInOrder()
216231
preds = tuple(set() for i in range(self.block_count))
@@ -297,6 +312,7 @@ def process_one_block(block, modify=False):
297312
self.entry.insts = deletes + self.entry.insts
298313

299314
def getCode(self):
315+
self.optimizeStoreUnderscore()
300316
self.optimizeLoadFast()
301317
return super().getCode()
302318

0 commit comments

Comments
 (0)