Holger Bille
Holger Bille

Reputation: 2551

How do I lazy evaluate variables in a python eval expression

The scenario is that my user can supply an expression string for evaluation. It could be:

"power=(x**2+y**2)**0.5"

Then I get an input stream of data with labels. E.g.:

x ; y ; z
1 ; 2 ; 3
1 ; 3 ; 4

And I will output a stream of data like this:

x ; y ; z ; power
3 ; 4 ; 3 ; 5.0 
6 ; 8 ; 4 ; 10.0

But I would also give the user the possibility to use use more "expensive" variables like e.g. 'sum':

"mysum = sum + 5"

But I don't want to calculate the 'sum' unless it is needed

So how do I best lazy evaluate the variables in the expression? Performance is important, but not overly so.

Clear and understandable code is most important

I have tried to ask the question before - How do I detect variables in a python eval expression. But apparently not being very concise

I am using eval and namespace for it currently. Other methods are also welcome.

Another approach that could give better performance is to detect all included variables in the user expression to know beforehand what precalculated variables will be needed.

A good answer to that would also be appreciated

Upvotes: 2

Views: 1060

Answers (1)

Holger Bille
Holger Bille

Reputation: 2551

The best solution to the question is also posted in the linked question:

import ast
def varsInExpression(expr):
    st = ast.parse(expr)
    return set(node.id for node in ast.walk(st) if type(node) is ast.Name)

This was posted by André Laszlo

It allows me to initialize the needed vars and functions before receiving any data and only precalculate "smart" variables that are used

The lazy evaluation part has not yet received a good answer

Upvotes: 1

Related Questions