1

I am creating a program which fits various curves to data. I am creating a number of functions which define a fit by doing the following:

for i in range(len(Funcs2)):
    func =  "+".join(Funcs2[i])
    func = func.format("[0:3]","[3:6]")
    exec('def Trial1{0}(x,coeffs): return {1}'.format(i, func))
    exec('def Trial1{0}_res(coeffs, x, y): return y - Trial1{0}
    (x,coeffs)'.format(i))

How do I then call each function of these created functions in turn. At the moment i am doing the following:

 for i in range(len(Funcs2)):
    exec('Trial1{0}_coeffs,Trial1{0}_cov,Trial1{0}_infodict,Trial1{0}_
          mesg,Trial1{0}_flag = 
          scipy.optimize.leastsq(Trial1{0}_res,x02, args=(x, y), 
          full_output = True)'.format(i))

In this loop, each created function is called in each iteration of the loop.The problem is that i have to keep using exec() to do want I want to do. This is probably bad practice and there must be another way to do it.

Also, i cannot use libraries other than numpy,scipy and matplotlib

Sorry for the bad formatting. The box can only take lines of code that are so long.

5
  • how is Func2 defined? Commented Apr 9, 2017 at 16:16
  • What is the contents of Funcs2? I doubt your first loop is a good idea in the first place. Commented Apr 9, 2017 at 16:16
  • Funcs2 is a list of tuples. Each tuple contains a 3 strings. I agree that the loop is a bad idea, but i could not think of another way to dynamically create and name functions Commented Apr 9, 2017 at 16:23
  • None of this sounds like a good idea to be honest. What makes you think you need dynamic functions? You just need normal functions that take parameters. Commented Apr 9, 2017 at 16:29
  • I could do that, but there are a lot of functions i want to create and using normal function would take a lot of code so i hoping to do this dynamically Commented Apr 9, 2017 at 16:34

1 Answer 1

4

Functions are first-class objects in python! You can put them in containers like lists or tuples, iterate through them, and then call them. exec() or eval() are not required.

To work with functions as objects instead of calling them, omit the parentheses.

EG:

def plus_two(x):
    return x+2
def squared(x):
    return x**2
def negative(x):
    return -x

functions = (plus_two, squared, negative)
for i in range(1, 5):
    for func in functions:
        result = func(i)
        print('%s(%s) = %s' % (func.__name__, i, result))

--> OUTPUT

plus_two(1) = 3
squared(1) = 1
negative(1) = -1
plus_two(2) = 4
squared(2) = 4
negative(2) = -2
plus_two(3) = 5
squared(3) = 9
negative(3) = -3
plus_two(4) = 6
squared(4) = 16
negative(4) = -4
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this it is really helpful.
Personally I think the use of f-strings makes the code harder to understand since f-strings are likely foreign to most readers. I think it would be better to split the function invocation and the printing of the result into separate statements (eg: result=func(i); print(...)`) which will make it more clear that you're calling the function rather than relying on some string processing voodoo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.