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)
8
  • 3
    Does this answer your question? How can I convert string to source code in python? Commented Apr 6, 2021 at 18:04
  • 5
    docs.python.org/3/library/functions.html#exec Commented Apr 6, 2021 at 18:05
  • 2
    Does eval work for turning strings to functions? Commented Apr 6, 2021 at 18:05
  • A def statement is not an expression. You would need to use exec, not eval. Use with caution. Commented Apr 6, 2021 at 18:06
  • How would I use exec? Commented Apr 6, 2021 at 18:08

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.