Dynamic Function Generation in Python: Complex Functions
Generating Complex Functions Dynamically:
Write a Python function “generate_complex_function” that takes a function name, a list of parameter names, and a body as strings, and returns a dynamically generated function.
Sample Solution:
Python Code :
Output:
5 5
Explanation:
- Function Definition:
- generate_complex_function takes 'name', 'params', and 'body' as input.
- It creates a string 'params_str' by joining 'params' with commas.
- It then creates 'indented_body' by replacing newline characters in 'body' with indented newlines, ensuring the code block is correctly formatted.
- 'func_code' constructs the function definition string using the formatted body.
- 'exec(func_code)' executes the generated function code.
- The generated function is retrieved from 'locals()'.
- Function Parameters and Body:
- function_name is set to 'complex_function'.
- parameters is set to ['x', 'y'].
- function_body contains the code to be executed within the function.
- Generate and Test the Function:
- complex_func is generated by calling "generate_complex_function".
- The generated function is tested by calling it with different arguments and printing the results.
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Python Dynamic Class Inheritance: Create Subclasses.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.