I'm using the Python ast module to obtain a list of variable names in a Python expression. 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]
. 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 -
['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
.