【发布时间】:2019-10-24 19:16:55
【问题描述】:
我必须分析包含 if 语句的 python 代码,我找到了 ast 模块:https://docs.python.org/3.8/library/ast.html 不知何故,文档不是不言自明的。 我在这里找到了一个例子:https://www.mattlayman.com/blog/2018/decipher-python-ast/ 它使用 ast.NodeVisitor 辅助类,但我正在努力如何采用此示例来获取 if 语句的详细信息。
要解析的代码:
toggleSwitch = False
# check for someValue in the key-value store
if 'someValue' in context['someKey']:
toggleSwitch = True
分析仪代码:
class Analyzer(ast.NodeVisitor):
def visit_If(self, node):
print("If:",node.test.left)
self.stats["if"].append(node.body)
self.generic_visit(node)
我希望在 visit_If 函数内访问节点的某种属性中的“someValue”元素,但我不知道该怎么做。
【问题讨论】:
标签: python if-statement abstract-syntax-tree