decorators

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:

CharacteristicDescription
DefinitionDecorators 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).
PurposeUsed to add functionality to functions or methods in a reusable and clean way.
Function WrapperDecorators are essentially wrappers that take a function as input and return a new function with added behavior.
Examplepython<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.
ChainingMultiple decorators can be applied to a single function, and they are executed in a nested fashion (bottom to top).
Built-in DecoratorsPython provides built-in decorators like @staticmethod, @classmethod, and @property for methods in classes.
Custom DecoratorsCan be created by defining a function that takes a function as an argument and returns a new function (e.g., def my_decorator(func):).
UsageCommonly used for logging, access control, memoization, validation, and more.
Function SignatureDecorators can alter or extend the behavior of the original function without changing its signature.
Preserving MetadataUse functools.wraps within a decorator to preserve the metadata (name, docstring) of the original function.
Example Codepython<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 DecoratorsDecorators can also be applied to classes, modifying or extending their behavior (e.g., adding methods, modifying attributes).
Decorators with ArgumentsDecorators can accept arguments to customize their behavior (e.g., @repeat(3) where repeat is a decorator factory).
#reviewed #python #online #programming-language #algorithms #advanced #ready