newbie: generate a function based on an expression
Mike Meyer
mwm at mired.org
Tue Dec 13 02:05:09 EST 2005
"Jacob Rael" <jacob.rael at gmail.com> writes:
> Hello,
> I would like write a function that I can pass an expression and a
> dictionary with values. The function would return a function that
> evaluates the expression on an input. For example:
>
> fun = genFun("A*x+off", {'A': 3.0, 'off': -0.5, 'Max': 2.0, 'Min':
> -2.0} )
>
>>>> fun(0)
> -0.5
>>>> fun(-10)
> -2
>>>> fun(10)
> 2
>
> so fun would act as if I did:
>
> def fun(x):
> A = 3
> off = -0.5
> Max = 2
> Min = -2
> y = min(Max,max(Min,A*x + off))
> return(y)
>
> Any ideas?
>>> def genFun(expr, ns):
... def fun(x):
... newns = dict(ns)
... newns['x'] = x
... return eval(code, newns)
... code = compile("min(Max, max(Min, %s))" % expr, 'genFun', 'single')
... return fun
Having said that, this is a *very* insecure thing to do. If you'd let
us know why you want to do this, we might be able to suggest a safer
way.
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list