Decorators are a highly valuable advanced programming feature in Python that modify or enhance the behavior of functions, methods, or classes without directly altering their code structure. Fundamentally, a decorator is a function that accepts another function as an argument and returns a new function.
One key advantage of using decorators is improving code reusability and readability, as well as enabling Aspect-Oriented Programming (AOP). This allows developers to add supplementary functionalities—such as logging, performance testing, and transaction handling—without modifying the original business logic.
Example:
pythonimport time def time_logger(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"{func.__name__} runtime: {end_time - start_time} seconds") return result return wrapper @time_logger def example_function(numbers): return sum(numbers) result = example_function([1, 2, 3, 4, 5])
In the above code, time_logger is a decorator that accepts a function func and defines another function wrapper. Within wrapper, we record the time before and after func executes to compute its runtime. Using the @time_logger syntax, this decorator is applied to example_function, and when calling example_function, it effectively invokes the wrapper function returned by time_logger.
By leveraging decorators, we can effortlessly add identical functionality to multiple functions without altering their internal implementations, thereby significantly enhancing code maintainability and extensibility.