2

Is there a way to convert a string value to a function? If this simply isn't doable with python, please let me know.

For example, I would like to convert this string:

'''
def greet(name):
    return f'Hello, {name}'
'''

to this function:

def greet(name):
    return f'Hello, {name}'

In a program, the example might look like:

function_string = '''
def greet(name):
    return f'Hello, {name}'
'''

def str_to_func(string):
    # Function body...

str_to_func(function_string)
JajasPer
  • 81
  • 9
  • 3
    Does this answer your question? [How can I convert string to source code in python?](https://stackoverflow.com/questions/43878504/how-can-i-convert-string-to-source-code-in-python) – mcsoini Apr 06 '21 at 18:04
  • 5
    https://docs.python.org/3/library/functions.html#exec – khelwood Apr 06 '21 at 18:05
  • 2
    Does `eval` work for turning strings to functions? – JajasPer Apr 06 '21 at 18:05
  • A `def` statement is not an expression. You would need to use `exec`, not `eval`. Use with caution. – khelwood Apr 06 '21 at 18:06
  • How would I use `exec`? – JajasPer Apr 06 '21 at 18:08
  • Oh okay, nevermind. I understand. Thank you @khelwood ! – JajasPer Apr 06 '21 at 18:09
  • I'm just curious as to why? It could be an XY problem, are you maybe importing what's otherwise python script, but is being read as strings? – BruceWayne Apr 06 '21 at 18:39
  • Except in really specific cases best to avoid evals or execs they are a big security risk. If it’s your code you can import it on demand, given its dotted path. [importlib](https://docs.python.org/3/library/importlib.html)can help with that. – JL Peyret Apr 08 '21 at 01:46

1 Answers1

3

here's an example use exec

function_string = '''
def greet(name):
    return f'Hello, {name}'

print(greet('john'))
'''

exec(function_string)

output :

Hello, john
kiranr
  • 2,087
  • 14
  • 32