简体   繁体   English

ast 节点不保留某些属性(lineno 或/和 col_offset)

[英]ast nodes not preserving some properties (lineno or/and col_offset)

I'm trying to convert every break statement with exec('break') in a code.我正在尝试在代码中使用exec('break')转换每个break语句。 So far I've got this:到目前为止,我有这个:

import ast

source = '''some_list = [2, 3, 4, 5]
for i in some_list:
    if i == 4:
        p = 0
        break
exec('d = 9')'''
tree = ast.parse(source)

class NodeTransformer(ast.NodeTransformer):
    def visit_Break(self, node: ast.Break):
        print(ast.dump(node))
        exec_break = ast.Call(func=ast.Name(id='exec', ctx=ast.Load()),
                              args=[ast.Constant(value='break')],
                              keywords=[])
        return ast.copy_location(exec_break, node)

NodeTransformer().visit(tree)
print(ast.unparse(tree))

However, at the end it outputs p = 0 and exec('break') at the same line:但是,最后它在同一行输出p = 0exec('break')

some_list = [2, 3, 4, 5]
for i in some_list:
    if i == 4:
        p = 0exec('break')
exec('d = 9')

I created the ast.Call object to the exec function with first argument 'break' but it seems not to transform properly.我使用第一个参数'break'创建了 ast.Call object 到 exec function,但它似乎没有正确转换。 What did I miss?我错过了什么?

I've found the bug.我发现了这个错误。 The ast.Call node has to be an ast.Expr object: ast.Call 节点必须是 ast.Expr object:

def visit_Break(self, node: ast.Break):
    exec_break = ast.Call(func=ast.Name(id='exec', ctx=ast.Load()),
                          args=[ast.Constant(value='break')],
                          keywords=[])
    new_node = ast.Expr(value=exec_break)
    ast.copy_location(new_node, node)
    ast.fix_missing_locations(new_node)
    return new_node

Reference: https://greentreesnakes.readthedocs.io/en/latest/examples.html#simple-test-framework参考: https://greentreesnakes.readthedocs.io/en/latest/examples.html#simple-test-framework

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型化节点评估 - typed-ast nodes evaluation 将 AST 节点转换为向量/数字 - Transform AST nodes into vectors/numbers Python:使用lineno引发SyntaxError - Python: raise SyntaxError with lineno 在Python 3中对数据框进行过采样以保留其统计属性的最佳方法是什么? - What is the best way to oversample a dataframe preserving its statistical properties in Python 3? 如何检索SyntaxError的文件名和lineno属性 - How to retrieve filename and lineno attribute of SyntaxError 如何计算图中节点对networkx中某些特殊节点的接近中心性? - How to calculate closeness centrality of nodes in a graph, toward some special nodes in networkx? 当某些列是datetime.time类型时,如何按列名对df进行切片? - How to slice df by col name when some of the columns are of datetime.time type? 使用基于某些数据的节点和顶点构造图形 - Constructing graph using nodes and vertices based on some data 如何创建不可变对象的副本并更新某些属性? - How to create a copy of an immutable object and update some properties? [networkx]可视化图形上的某些点,这些点沿链接移动,但它们不是节点 - [networkx]Visualise some points on a graph, the points move along the link, but they are not nodes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM