Nataly Firstova
Nataly Firstova

Reputation: 821

Python convert string to function and execute it

I have several functions in the database as a strings and there is a main function that should take these functions from the database and execute them as functions, and not as text.

How I can transform a string (which describes a function) into a function with arguments and execute it in Python?

I'm tried exec but I can't return something from function and use it.

For example my function:

some_function = """
def my_random_function(some_param):
    print(some_param)
    return time.time()
"""

Upvotes: 3

Views: 2190

Answers (2)

tandat
tandat

Reputation: 255

Function defined by exec can work like normal function, and of course you can also get the return values. Make sure you have import all the essential libraries (time in your example)

import time

some_function = """
def my_random_function(some_param):
    print(some_param)
    return time.time()
"""

exec(some_function)
return_value = my_random_function(3)
print(return_value)

output

3
1637328869.3345668

Upvotes: 0

Keegan Cowle
Keegan Cowle

Reputation: 2479

100% Never do this ever under any circumstances disclaimer...

the exec statement:

code = """
def f(x):
    x = x + 1
    return x

print('This is my output.')
print(f(my_var))
"""

exec(code, {}, {"my_var": 1})

output:

This is my output.
2

Upvotes: 3

Related Questions