[英]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 = 0
和exec('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.