def add_before_node(ast_root, before_node, node_to_add):
"""Attempts to add node_to_add before before_node
For example, if you had the code:
def foo(j):
for i in range(j):
print(i)
and before_node was "for i in range(j):" and node_to_add was "print(2)",
the result would be:
def foo(i):
print(2)
for i in range(j):
print(i)
"""
node, parent = find_node_recursive(ast_root, before_node)
if node is None:
raise ValueError("Node %s not found in ast: %s" % (
str(before_node),
dump_ast(before_node)))
for field, value in ast.iter_fields(parent):
if isinstance(value, list):
for i in range(len(value)):
if isinstance(value[i], ast.AST) and \
nodes_are_equal(value[i], node):
value.insert(i, node_to_add)
return
评论列表
文章目录