comments? storing a function in an object
Carl Banks
pavlovevidence at gmail.com
Mon Jul 20 23:53:53 EDT 2009
On Jul 20, 9:22 am, Esmail <ebo... at hotmail.com> wrote:
> def funct1(x):
> ''' small test function '''
> return x * x
>
> def funct2(x, y):
> ''' small test function '''
> return x + y
>
> def funct3(x):
> ''' small test function '''
> return 1000 + (x*x + x) * math.cos(x)
>
> def main():
> """ main method """
> print 'in main'
>
> fn1 = Function(funct1, 'x * x', 1)
> fn2 = Function(funct2, 'x + y', 2)
> fn3 = Function(funct3, '1000 + (x*x + x) * cos(x)', 1)
If you are defining all of the functions are in-line like this (and I
assume you are because you seem to need a function object), I'd just
exec the string representation. This is to support the DRY
principle. You could do something like this:
class Function(object):
def __init__(self,args,body):
ns = {}
exec '''def func(%s): return %s''' in ns
self.fn = ns['func']
self.fn_str = body
self.num_vars = args.count(',')+1
You have to be REALLY REALLY careful not to pass any user-supplied
data to it if this is a server running on your computer, of course.
(If it's an application running on the user's computer it doesn't
matter.)
Still wouldn't be a bad idea to pass it through some kind of validator
for extra protection.
Carl Banks
More information about the Python-list
mailing list