Python Code Generation: Transform Templates
Generating Functions Dynamically:
Write a Python function “generate_function” that takes a function name and a body as strings, and returns a dynamically generated function.
Sample Solution:
Python Code :
Output:
Hello from the dynamically generated function!
Explanation:
- Function Definition:
- "generate_function" takes 'name' (the function name) and 'body' (a string containing the function body).
- Execute Function Code:
- exec(f"def {name}():\n {body}") dynamically defines and executes the function code in the local scope.
- Return Generated Function:
- The generated function is retrieved from 'locals()' and returned.
- Function Name and Body:
- 'function_name' is set to 'dynamic_function'.
- 'function_body' contains the code to be executed within the function.
- Generate the Function:
- 'dynamic_func' is generated by calling 'generate_function'.
- Test the Function:
- The generated function "dynamic_func" is tested by calling it, which prints the message "Hello from the dynamically generated function!".
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Python Code Generation: Transform Templates.
Next: Python Dynamic Class Inheritance: Create Subclasses.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.