【问题标题】:How to work with python ast module to analyse if-statements如何使用 python ast 模块分析 if 语句
【发布时间】: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


    【解决方案1】:

    GreenTreeSnakes 在 Python AST 树中的节点上有相当丰富的文档。

    我不知道您是否真的将代码解析为 ast 树,所以我将在此处包含它。

    将代码解析成树:

    code = '''toggleSwitch = False
    
    # check for someValue in the key-value store
    if 'someValue' in context['someKey']:
        toggleSwitch = True'''
    
    import ast
    tree = ast.parse(code)
    

    然后在您的 Analyzer 类中,您可以从 _ast.Str 节点的 s 属性中获取 someValue 符号。

    class Analyzer(ast.NodeVisitor):
        def __init__(self):
            self.stats = {'if': []}
    
        def visit_If(self, node):
            # Add the "s" attribute access here
            print("If:", node.test.left.s)
            self.stats["if"].append(node.body)
            self.generic_visit(node)
    
        def report(self):
            pprint(self.stats)
    
    >>> a = Analyzer()
    >>> a.visit(tree)
    If: someValue
    

    对于If 节点,属性为test (_ast.Compare) → left (_ast.Str) → s (str)。

    【讨论】:

    • 非常感谢,这真的很有帮助。现在如何访问右侧“in context['someKey']”?你也有这方面的想法吗?
    • 这些将在_ast.Compare 节点的其他属性中,特别是ops(“in”)和comparators(其他所有属性)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多