Contents
Roadmap info from roadmap website
Decorators
decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
Visit the following resources to learn more:
Characteristic | Description |
---|---|
Definition | Decorators are functions that modify or extend the behavior of other functions or methods. |
Syntax | @decorator_name applied above the function definition (e.g., @my_decorator ). |
Purpose | Used to add functionality to functions or methods in a reusable and clean way. |
Function Wrapper | Decorators are essentially wrappers that take a function as input and return a new function with added behavior. |
Example | python<br>@my_decorator<br>def my_function():<br> pass <br>my_function is passed to my_decorator , which returns a modified version of my_function . |
Chaining | Multiple decorators can be applied to a single function, and they are executed in a nested fashion (bottom to top). |
Built-in Decorators | Python provides built-in decorators like @staticmethod , @classmethod , and @property for methods in classes. |
Custom Decorators | Can be created by defining a function that takes a function as an argument and returns a new function (e.g., def my_decorator(func): ). |
Usage | Commonly used for logging, access control, memoization, validation, and more. |
Function Signature | Decorators can alter or extend the behavior of the original function without changing its signature. |
Preserving Metadata | Use functools.wraps within a decorator to preserve the metadata (name, docstring) of the original function. |
Example Code | python<br>from functools import wraps<br><br>def my_decorator(func):<br> @wraps(func)<br> def wrapper(*args, __kwargs):<br> print("Something is happening before the function is called.")<br> return func(*args, __kwargs)<br> return wrapper<br><br>@my_decorator<br>def say_hello(name):<br> print(f"Hello {name}") |
Class Decorators | Decorators can also be applied to classes, modifying or extending their behavior (e.g., adding methods, modifying attributes). |
Decorators with Arguments | Decorators can accept arguments to customize their behavior (e.g., @repeat(3) where repeat is a decorator factory). |