def test_replace_non_existant(self): root = ast.parse('a = 1') name_a = root.body[0].targets[0] name_b = ast.Name(id='b', ctx=ast.Store()) replace_nodes(root, name_b, name_a) expected = ast.parse('a = 1') assert_ast_eq(self, root, expected)
def remove_unused_assign(root, symbol): ''' Remove redundant statements. The statement `a = 1` will be removed:: a = 1 a = 2 The statement `a = 1` will not be removed because `b` depends on it:: a = 1 b = a + 2 a = 2 :param root: ast node ''' gen = GatherAssignments() gen.visit(root) to_remove = [] if symbol not in gen.assign_id_map: return assignments = gen.assign_id_map[symbol] if len(assignments) < 2: return for j in range(len(assignments) - 1): i1 = root.body.index(assignments[j].root) i2 = root.body.index(assignments[j + 1].root) body = root.body[i1 + 1:i2] grapher = GraphGen() for stmnt in body: grapher.visit(stmnt) if symbol not in grapher.used: to_remove.extend(assignments[j].assignments) Pass = lambda node: _ast.Pass(lineno=node.lineno, col_offset=node.col_offset) for old in to_remove: replace_nodes(root, old, Pass(old))