Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
"""
like image 348
Nataly Firstova Avatar asked Jul 22 '26 05:07

Nataly Firstova


1 Answers

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
like image 115
testfile Avatar answered Jul 23 '26 19:07

testfile



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!