Python saves the eval function

Let's say I have a function fun(f, x, y)where x and y are numbers, and f is a string defining a function such as "1 / x ** 2 + y".

I want to use this function fmany, say, several million times, and the values xand ychange between each use.
Therefore, the call eval(f)takes a considerable amount of time, and not just calculates the value of the function each time. (About 50x, in my measured case.)

Is there a way to save this function fso that I only need to call it once eval?

PS. Please do not discuss the (in) security of use evalhere, I know about it, but this code will not go anywhere when it is launched by a third party, and this does not apply to my question.

+6
source share
1 answer

You can eval lambda, so you just evaluate it once, and after that it is a function that you can use:

s = "1 / x ** 2 + y"

s = "lambda x,y: "+s
f = eval(s)
x = 2
y = 3
print(f(x,y))

I get 3.25, but I can change x, and yas many times as you need, without evaluating the expression again.

+9
source

Source: https://habr.com/ru/post/1016976/


All Articles