210. Automatic Code Generation
πΉ 1. Generating a Function Dynamically Using exec
execcode = """
def greet(name):
return f"Hello, {name}!"
"""
exec(code)
print(greet("Alice")) # Hello, Alice!πΉ 2. Creating a Class Dynamically Using exec
execclass_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.πΉ 3. Generating Functions with exec Using a Loop
exec Using a LoopπΉ 4. Using eval to Execute Simple Expressions
eval to Execute Simple ExpressionsπΉ 5. Generating a Lambda Function with eval
evalπΉ 6. Creating a Dynamic Dictionary Using exec
execπΉ 7. Dynamically Creating Properties in a Class
πΉ 8. Creating a Custom Function Generator
πΉ 9. Using eval to Create List Comprehensions
eval to Create List ComprehensionsπΉ 10. Securely Using exec with a Limited Namespace
exec with a Limited Namespaceπ Final Thoughts
Last updated