Question

I want to have a dictionary where the value is a statement. I don't need to build the statement dynamically. The names appearing in the statement are in the local scope. A simple example appears below. It seems like 'exec' is the thing to use, but this appears to be frowned upon, and is probably slow. This code will be used in a stochastic modeler, and will be run gazillions of times. Could you suggest to me how to best accomplish this idea (maybe by precompiling?). Could it be I already have this right?

Cheers!

Jeff

d={'plusone':'x+=1','minusone':'x-=1'}
x=2
exec(d['plusone'])
print x  ::: output '3'
exec(d['minusone'])
print x  ::: output '2'
Was it helpful?

Solution

Presumably you are doing exec(d['plusone']) in some scope wherein x is defined, otherwise you would get a NameError.

It seems far better to put a callable into your dict and explicitly pass it x (and explicitly assign to x):

from operator import add, sub

d={'plusone':lambda x: add(x,1), 'minusone':lambda x: sub(x,1)}

x = 2

x = d['plusone'](x)

x
Out[17]: 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top