简体   繁体   English

ast - 获取表达式中仅包含变量名的列表

[英]ast - Get the list of only the variable names in an expression

I'm using the Python ast module to obtain a list of variable names in a Python expression.我正在使用 Python ast 模块来获取 Python 表达式中的变量名称列表。 For example, the expression [int(s[i:i + 3], 2) for i in range(0, len(s), 3)] should return a singleton list with the variable name s like [s] .例如,表达式[int(s[i:i + 3], 2) for i in range(0, len(s), 3)]应该返回一个 singleton 列表,其变量名称 s 类似于[s] I've tried the following code snippet -我尝试了以下代码片段 -

names = [
    node.id for node in ast.walk(ast.parse(formula)) 
    if isinstance(node, ast.Name)
]

which returns a list of variables plus function names in the ast -它返回一个变量列表加上 ast 中的 function 个名称 -

['int', 'i', 's', 'range', 'i', 'len', 's', 'i']

But I don't want to include function names like range , len , int and the iterator i .但我不想包含 function 名称,如rangelenint和迭代器i

You can use similar approach but then filter out names from builtins.您可以使用类似的方法,但随后会从内置函数中过滤掉名称。 Something like this像这样的东西

import ast
import builtins

def get_variables(expression):
    tree = ast.parse(expression)
    variables = []
    for node in ast.walk(tree):
        if isinstance(node, ast.Name):
            variables.append(node.id)
    return tuple(v for v in set(variables) if v not in vars(builtins))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM