w3resource

Dynamic Function Generation in Python: Complex Functions

Python Metaprogramming: Exercise-12 with Solution

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 :

# Function to generate a complex function dynamically
def generate_complex_function(name, params, body):
    # Join the parameters with commas to form the parameter string
    params_str = ', '.join(params)
    
    # Properly indent the function body
    indented_body = body.replace('\n', '\n    ')
    
    # Construct the function code string
    func_code = f"def {name}({params_str}):\n    {indented_body}"
    
    # Execute the function code in the local scope
    exec(func_code)
    
    # Return the generated function from the local scope
    return locals()[name]

# Define function parameters and body
function_name = 'complex_function'
parameters = ['x', 'y']
function_body = """
if x > y:
    return x - y
else:
    return y - x
"""

# Generate the function
complex_func = generate_complex_function(function_name, parameters, function_body)

# Test the dynamically generated function
print(complex_func(10, 5))  # Output: 5
print(complex_func(5, 10))  # Output: 5

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/metaprogramming/python-metaprogramming-exercise-12.php