Python decorators
Decorators are a design pattern that allow to modify the behaviour of function as wrappers, they use the special @ syntax, as an example:
import functools
import time
def measure_time(func):
@functools.wraps(func) # Preserves the original function metadata
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time:.2f} seconds to execute")
return result
return wrapper
# Using the decorator
@measure_time
def slow_function():
time.sleep(1)
return "Done!"
# Then to import it:
# main.py
from decorators import measure_time
@measure_time
def my_function():
pass
Some built-in decorators are:
@property: Transforms a method into a getter property
@classmethod: Converts and object method into a class method
@staticmethdo: Converts a method into a static method
@abstractmethod: Abstract method for abstract classes
@contextmanager: used in Python Context Manager
@dataclass: (Python 3.7+), Creates a data class Python data class