tags:

views:

44

answers:

1

Is there a way to get python to do an evaluation and execution on a string? I have a file which contains a bunch of expressions that need to be calculated, maybe something like this.

f1(ifilter(myfilter,x))
f2(x)*f3(f4(x)+f5(x))

I run through the file and eval the expressions.

Some of the expressions may want to save their work after doing an expensive operation

y = g(x); h(y)+j(y)

Unfortunately, y=g(x) requires an exec, but getting the value of h+j is an eval. How does this work?

A: 

Try using the builtin compile(). When you use it in single mode it handles both of the cases that you want. For example:

compile('3+4','<dummy>','single')

will return a compiled code object. You can execute it with exec() or eval() :

>>> exec(compile('3+4','<dummy>','single'))
7
>>> exec(compile('x=3+4','<dummy>','single'))
>>> print x
7
Amoss