Decorators for Logging Functions
Decorators are particularly useful for adding logging functionality to your Python functions. By using a decorator, you can easily log the function call, its arguments, and the return value without modifying the function's source code.
Here's an example of a simple logging decorator:
def log_function_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args={args} and kwargs={kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@log_function_call
def add_numbers(a, b):
return a + b
result = add_numbers(2, 3)
print(result)
In this example, the log_function_call
decorator wraps the add_numbers
function, logging the function call and its return value. The @log_function_call
syntax applies the decorator to the add_numbers
function.
You can also create more sophisticated logging decorators that include additional information, such as the current time, the duration of the function call, or the function's docstring. Here's an example:
import time
from functools import wraps
def log_function_call(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
print(f"Calling {func.__name__} at {start_time:.2f} with args={args} and kwargs={kwargs}")
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} returned {result} in {end_time - start_time:.2f} seconds")
return result
return wrapper
@log_function_call
def add_numbers(a, b):
"""Add two numbers and return the result."""
return a + b
result = add_numbers(2, 3)
print(result)
In this example, the log_function_call
decorator logs the function call time, the function arguments, the return value, and the execution time of the function.
Decorators for logging functions can be a powerful tool for debugging, profiling, and understanding the behavior of your Python code.