Ask Your Question
2

How can function parameters be transferred into a new function body based on a code that is in string format?

asked 2023-06-16 06:28:19 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-16 06:40:02 +0000

plato gravatar image

You can use the eval() function in Python to convert a string into a code object and then call it with the necessary parameters. Here is an example:

def my_func(param1, param2):
    code_str = "print('Param1:', param1)\nprint('Param2:', param2)"
    code_obj = compile(code_str, "<string>", "exec")
    eval(code_obj, {"param1": param1, "param2": param2})

my_func("hello", 42)
# Output:
# Param1: hello
# Param2: 42

In this example, my_func() takes two parameters (param1 and param2) and then creates a code string that prints the values of these parameters. The compile() function is used to convert the string into a code object, and eval() is used to execute the code while passing in the parameters as a dictionary. The output shows that the parameters have been successfully transferred into the new function body.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-16 06:28:19 +0000

Seen: 9 times

Last updated: Jun 16 '23