Timed execution in eval

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Mar 7 23:07:26 CET 2008

On Fri, 07 Mar 2008 08:12:38 -0800, alex.pedwysocki wrote:

> I have various bits of code I want to interpret and run at runtime in
> eval ...

I hope that code doesn't contain any data coming from an untrusted user.

> I want to be able to detect if they fail with error,

That's what try...except blocks are for.

    x = eval('1 + 1 = 2')
except SyntaxError:
    x = 3

> I want to be able to time them, 

That's what the timeit module is for.

If you do time them, you will find that eval(expr) is MUCH MUCH slower 
than just executing expr as normal.

>>> from timeit import Timer
>>> Timer('1+1').timeit()
>>> Timer('eval("1+1")').timeit()

If you use eval() a lot, you will have a SLOW program.

> and I want to be able to stop them if they run too long. 

That's tricky. As far as I know, the only way for a Python program to 
stop an arbitrary calculation after a certain period of time it to run it 
in a thread. You then monitor the elapsed time, and when the timer 
expires, ask the thread to die. And hope it listens.

> I cannot add code to the eval'd strings that will help me accomplish
> this.

You can't? Why ever not?

Note: that's almost certainly the wrong way to solve your problem, but 
I'm curious as to why you can't.


More information about the Python-list mailing list