w3resource

Python Code Generation: Transform Templates

Python Metaprogramming: Exercise-9 with Solution

Generating Code from Templates:

Write a Python function "generate_code" that takes a template string with placeholders and a dictionary of values, and returns the generated code with placeholders replaced by corresponding values.

Sample Solution:

Python Code :

# Function to generate code from a template and values
def generate_code(template, values):
    # Format the template with the provided values
    return template.format(**values)

# Define a template for a class
template = """
class {class_name}:
    def __init__(self, {args}):
        {init_body}
"""

# Define values to replace placeholders in the template
values = {
    'class_name': 'Person',  # Class name
    'args': 'name, age',     # Constructor arguments
    'init_body': 'self.name = name\n        self.age = age'  # Initialization body
}

# Generate the code by formatting the template with the values
generated_code = generate_code(template, values)

# Print the generated code (commented out to avoid execution in this example)
# print(generated_code)

# Execute the generated code to define the class
exec(generated_code)

# Test the dynamically generated class
person = Person('Diocles', 25)  # Create an instance of the generated class
print(person.name)  # Output: 'Diocles'  # Access the name attribute
print(person.age)   # Output: 25        # Access the age attribute

Output:

Diocles
25

Explanation:

  • Function Definition:
    • generate_code takes template (a string with placeholders) and values (a dictionary with values to replace the placeholders).
  • Format Template:
    • The template is formatted using template.format(**values), which replaces the placeholders with corresponding values from the dictionary.
  • Template Definition:
    • 'template' is a string defining a class structure with placeholders for the class name, constructor arguments, and initialization body.
  • Values Definition:
    • 'values' is a dictionary containing:
      • class_name: The name of the class to be generated.
      • args: The arguments for the class constructor.
      • init_body: The initialization code for the constructor.
  • Generate Code:
    • 'generated_code' is created by formatting the 'template' with 'values'.
  • Print Generated Code:
    • The generated code is printed (commented out in this example to avoid execution issues).
  • Execute Generated Code:
    • exec(generated_code) executes the generated code, defining the 'Person' class.
  • Test Generated Class:
    • An instance of the 'Person' class is created with the name 'Diocles' and age 25.
    • The 'name' and 'age' attributes of the instance are accessed and printed.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Python Dynamic Class Inheritance: Expand with Subclass.
Next: Python Code Generation: Transform Templates.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.