functools
is a module in Python that provides higher-order functions and operations on callable objects (e.g., functions). It contains several decorators that can be used to modify or extend the behavior of functions. Here are some commonly used decorators from functools
:
@wraps
:
This decorator is used to preserve the original function's metadata (e.g., name, docstring) when creating a new wrapper function.
It ensures that the decorated function appears as its original self when inspected or introspected.
Example:
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello(name):
"""A simple function that greets the user."""
return f"Hello, {name}!"
print(say_hello.__name__) # Output: "say_hello"
print(say_hello.__doc__) # Output: "A simple function that greets the user."
@lru_cache
:
This decorator is used for memoization, which caches the results of function calls with the same input arguments, avoiding unnecessary recomputation.
It is particularly useful when dealing with recursive functions or functions with expensive computations.
Example:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10)) # Output: 55
@partial
:
This decorator is used to create partial functions by fixing certain arguments of a function, creating a new function with fewer arguments.
It allows you to create specialized versions of functions for specific use cases.
Example:
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(5)) # Output: 25
These decorators from functools
are powerful tools to enhance the functionality and maintainability of your Python code. They provide features like preserving metadata, caching expensive function calls, and creating specialized versions of functions with fewer arguments.