210. Automatic Code Generation
πΉ 1. Generating a Function Dynamically Using exec
execCopy
code = """
def greet(name):
return f"Hello, {name}!"
"""
exec(code)
print(greet("Alice")) # Hello, Alice!π How it works:
execruns the string as Python code, defininggreetat runtime.
πΉ 2. Creating a Class Dynamically Using exec
execCopy
class_code = """
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
return f"{self.name} is {self.age} years old."
"""
exec(class_code)
p = Person("Bob", 25)
print(p.info()) # Bob is 25 years old.π How it works:
Defines a class dynamically and instantiates an object.
πΉ 3. Generating Functions with exec Using a Loop
exec Using a LoopCopy
π How it works:
Creates
square_0,square_1, andsquare_2functions dynamically.
πΉ 4. Using eval to Execute Simple Expressions
eval to Execute Simple ExpressionsCopy
π How it works:
evalevaluates a string as a Python expression.
πΉ 5. Generating a Lambda Function with eval
evalCopy
π How it works:
Dynamically creates a lambda function and evaluates it.
πΉ 6. Creating a Dynamic Dictionary Using exec
execCopy
π How it works:
Constructs a dictionary with dynamic keys.
πΉ 7. Dynamically Creating Properties in a Class
Copy
π How it works:
Uses
execto set class attributes dynamically.
πΉ 8. Creating a Custom Function Generator
Copy
π How it works:
Generates a function dynamically based on the operator.
πΉ 9. Using eval to Create List Comprehensions
eval to Create List ComprehensionsCopy
π How it works:
Uses
evalto generate a list dynamically.
πΉ 10. Securely Using exec with a Limited Namespace
exec with a Limited NamespaceCopy
π How it works:
Restricts
execto a limited namespace for safety.
π Final Thoughts
exec: Runs Python statements dynamically.eval: Evaluates expressions but should be used carefully.Use Cases: Dynamic class creation, function generation, code execution.
Last updated