jarsushi jarsushi - 1 year ago 47
Python Question

Define a function using string variable

I am trying to create a function "a21" that takes a parameter x and adds 4 to it.

eq = 'x+4'
def eval(new):
return eval(eq)


The desired output is 9 but it's not recognizing a21 as a function. How do I write this to create a the function a21 that also takes a parameter x?

Answer Source

Write a fully-featured function definition:

new = '''
def a21(x):
    return x + 4

And then execute it: exec(new) and run: a21(678).

If you want to construct a function during runtime, use string formatting.

new = '''
def {}({}):
    return {}

exec(new.format('test', 'x', 'x+4'))