Dynamic Code Execution and Code Generation in Python: Techniques and Practical Scenarios
This article explains Python's dynamic code execution and code generation techniques, covering the exec function, code templates, and six practical examples such as dynamic module import, class loading, function invocation, class definition, function creation, and runtime modification of classes or functions.
Dynamic code execution and code generation are common techniques in Python metaprogramming that allow code to be executed or generated at runtime. This article introduces the exec function and code templates, and presents several practical scenarios.
Dynamic code execution
Python provides the exec function to execute a string of code at runtime.
code = """
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
"""
exec(code)Code templates
Code templates are strings containing placeholders that can be replaced to generate final code. Python can create templates using the format method or template engines such as Jinja2.
template = """
def greet(name):
print(f"Hello, {name}!")
greet("{name}")
"""
code = template.format(name="Alice")
print(code)Below are six practical scenario codes covering dynamic module import, dynamic class loading, dynamic function calling, dynamic class definition, dynamic function creation, and dynamic modification of classes or functions.
1. Dynamic module import
module_name = "math"
module = __import__(module_name)2. Dynamic class loading
class_name = "MyClass"
module_name = "my_module"
module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()3. Dynamic function calling
function_name = "my_function"
module_name = "my_module"
module = __import__(module_name)
function = getattr(module, function_name)
result = function()4. Dynamic class definition
class_name = "MyClass"
base_classes = (BaseClass1, BaseClass2)
attributes = {"attr1": value1, "attr2": value2}
class_ = type(class_name, base_classes, attributes)5. Dynamic function creation
import types
def create_function(name, code):
function = types.FunctionType(compile(code, "", "exec"), globals(), name)
return function
code = """
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
"""
function = create_function("greet", code)
function()6. Dynamic modification of classes or functions
import types
def add_method(cls, method_name, method):
setattr(cls, method_name, method)
class MyClass:
pass
def new_method(self):
print("This is a new method.")
add_method(MyClass, "new_method", new_method)
obj = MyClass()
obj.new_method()These scenarios demonstrate how developers can use Python's dynamic features to create more flexible and extensible programs.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.