newbie: generate a function based on an expression

Michael Spencer mahs at telcopartners.com
Tue Dec 13 01:44:27 EST 2005


Jacob Rael wrote:
> 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?
> 
> jr
> 


You might prefer to write your expression as a real function, rather than a 
source string, so that it would be easier to test.

  >>> def fun(x, A, off, Max, Min):
  ...     return min(Max,max(Min,A*x + off))
  ...

Then you can "curry" in the constant values, using something like:

  >>> def getFun(fn, env_dict):
  ...     env_dict = env_dict.copy()
  ...     def fun_curry(x):
  ...         return fn(x,**env_dict)
  ...     return fun_curry
  ...
  >>> myenv = {'A': 3.0, 'off': -0.5, 'Max': 2.0,  'Min': -2.0}
  >>> fun1 = getFun(fun, myenv)
  >>> fun1(0)
  -0.5
  >>> fun1(0.5)
  1.0
  >>> fun1(-10)
  -2.0
  >>> fun1(10)
  2.0

HTH
Michael





More information about the Python-list mailing list