def assertDepends(self, source, edges, undefined=None, modified=None): mod = ast.parse(source) gen = GraphGen(call_deps=True) gen.visit(mod) self.assertSetEqual(set(gen.graph.edges()), edges) if undefined is not None: self.assertSetEqual(set(gen.undefined), undefined) if modified is not None: self.assertSetEqual(set(gen.modified), modified) tested.update(mod) return gen
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))