jarsushi jarsushi - 4 months ago 6
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'
b=21
new='a'+str(b)+'(x)'
def eval(new):
return eval(eq)

c=5
print(a21(c))


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

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'))

test(123)