如何在 Python 抽象语法树 (AST) 中获取实际用户定义的变量名?

How to get actual user defined variable name in Python Abstract Syntax Tree (AST)?

从下面给定的代码片段中,我尝试提取 python 内置变量以外的实际用户定义变量名称,以便根据我的命名约定规则检查它们。

ast_example.py

import ast
from pprint import pprint


def main():
    FirstName = "Johnny"
    LastName = "David"
    Variable_One = "Variable1"
    Variable_Two = "Variable2"
    Variable_Three = "Variable3"
    with open("ast_example.py", "r") as source:
        tree = ast.parse(source.read())

    analyzer = Analyzer()
    analyzer.visit(tree)
    analyzer.report()


class Analyzer(ast.NodeVisitor):
    def __init__(self):
        self.stats = {"variable": []}

    def visit_Name(self, node):
        print "Node: ",node.id
        self.stats["variable"].append(node.id)
        self.generic_visit(node)

    def report(self):
        pprint(self.stats)


if __name__ == "__main__":
    main()

然而,在我执行上面的代码片段后,它不仅产生了我想要的变量,而且还产生了每个 python 内置变量,例如 self__name__ , open, source, 等是我想排除的。

{'variable': ['FirstName',
              'LastName',
              'Variable_One',
              'Variable_Two',
              'Variable_Three',
              'open',
              'source',
              'tree',
              'ast',
              'source',
              'analyzer',
              'Analyzer',
              'analyzer',
              'tree',
              'analyzer',
              'ast',
              'self',
              'self',
              'self',
              'node',
              'self',
              'node',
              'self',
              'node',
              'self',
              'pprint',
              'self',
              '__name__',
              'main']}

如何排除那些内置变量?谢谢

您可能不想访问 Name,而是访问 Assign,这是表示赋值的节点。

所以代码看起来像这样:

def visit_Assign(self, node):
    for target in node.targets:
        self.stats["variable"].append(target.id)
    self.generic_visit(node)

这里targets,表示赋值的多个值如:a, b = 0, 1

ref: python ast doc