py_ast.py 文件源码

python
阅读 29 收藏 0 点赞 0 评论 0

项目:vizgen 作者: uva-graphics 项目源码 文件源码
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
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号