假设我有以下字符串:
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
以下代码将该字符串转换为 AST。
ast.parse(code)
然后我有一棵树:
Module(body=[<_ast.If object at 0x100747358>])
If(test=BoolOp(op=And(), values=[<_ast.Compare object at 0x100747438>, <_ast.Compare object at 0x100747a90>, <_ast.Compare object at 0x100747d68>]), body=[<_ast.Assign object at 0x100747e48>], orelse=[])
我想知道是否有办法转换对象at.If
到字符串中if 1 == 1 and 2 == 2 and 3 == 3:
我知道可以通过遍历子节点来完成,但是这样就变得太复杂了。
Python 3.9 推出ast.unparse https://docs.python.org/3/library/ast.html#ast.unparse这正是这样做的,即它反转了ast.parse
。使用你的例子:
import ast
code = """
if 1 == 1 and 2 == 2 and 3 == 3:
test = 1
"""
tree = ast.parse(code)
print(ast.unparse(tree))
这将打印出:
if 1 == 1 and 2 == 2 and (3 == 3):
test = 1
请注意,原始输入可能略有不同。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)