# L-25 MCS 507 Wed 19 Oct 2011 : make_funcode.py

# Executing a class definition inside a function 
# gives a tool for turning code defined
# in a string into a callable object.

def makefunction(code):
   """
   Given in a string code
   with input in x, output to y
   returns a callable object.
   """
   classdefinition = """
class myfunction:

   def __init__(self,expression):
      self.code = expression

   def __str__(self):
      return self.code

   def __call__(self,x,dp=15):
      exec(self.code)
      return y
"""
   exec(classdefinition)
   return myfunction(code)

def main():
   """
   Turns code into a function.
   """
   program = """
import sympy as sp
from sympy.mpmath import *
t = sp.var('t')
e = sp.exp(-t**2)*sp.sin(2*sp.pi*t)
mp.dps = dp
mpfx = mpf(str(x))
w = sp.Subs(e,(t),(mpfx)).doit()
y = w.evalf(dp)
"""
   p = makefunction(program)
   print 'the program :', p
   u = 2.3
   w = p(u,30)
   print 'evaluated at', u, ':', w

if __name__=="__main__": main()
