w3resource

Python Code Generation: Transform Templates

Python Metaprogramming: Exercise-10 with Solution

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 :

# Function to generate a function dynamically
def generate_function(name, body):
    # Execute the function code in the local scope
    exec(f"def {name}():\n    {body}")
    # Return the generated function from the local scope
    return locals()[name]

# Define the function name and body
function_name = 'dynamic_function'
function_body = "print('Hello from the dynamically generated function!')"

# Generate the function
dynamic_func = generate_function(function_name, function_body)

# Test the dynamically generated function
dynamic_func()  # Output: "Hello from the dynamically generated function!"

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.



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://www.w3resource.com/python-exercises/metaprogramming/python-metaprogramming-exercise-10.php