What are Decorators?
Let's discuss decorators.
Note that "Decorators" can be a challenging topic for beginners. We will examine decorators in detail, step by step, explaining how they work, but it may be challenging to comprehend. Are you prepared for the challenges? That's why you're here!
Note
The prerequisite topic for understanding decorators is closure. Therefore, make sure you understand how closure works before diving into decorators.
Decorators
Decorators are functions that add extra functionality to another function using the closure.
1234567891011121314151617181920def decorator(func): def wrapper(argument1, argument2): print("Function starts executing") result = func(argument1, argument2) print("Function ends executing") return result return wrapper def add(a, b): print(f"Function add: {a} + {b}") return a + b add = decorator(add) print(add(14, 12)) print(add(11, 28)) print(add(33, 16))
Here is an example of how a decorator works. The decorator()
function takes a function as an argument, defines the wrapper()
function, encloses the taken function within the wrapper()
, and returns the wrapper()
. There are three steps to the decorator's work:
Taking a function as an argument.
Enclosing the function within the newly defined function (
wrapper
).Returning the
wrapper
function with the enclosed function.
The wrapper()
function contains the main decorator logic and invokes the function with the given parameters.
The add()
function is reassigned by the returned wrapper()
function that now contains the enclosed add()
function.
python9123add = decorator(add) # decorator() encloses add()add = wrapper # wrapper() has enclosed add() function
Decorator Implementing
Step 1. Define the decorator.
The decorator should take exactly one argument.
pythondef decorator(func):
Step 2. Define the inner function.
We need to define the inner function to close the function taken by decorator()
.
python912def decorator(func):def wrapper():
Step 3. Enclose the taken function.
The function should be called inside the inner function (wrapper
), and the result should be saved and returned.
python91234def decorator(func):def wrapper():result = func()return result
Step 4. Return the inner function.
The decorator should return the inner function wrapper
without calling.
python912345def decorator(func):def wrapper():result = func()return resultreturn wrapper
How does the decorator work?
Step 1: Decorator is called.
The decorator()
function is called and takes the function (decorated function) as the argument func
. At this step, the interpreter creates the decorator()
local scope.
pythonfunction = decorator(function)
Step 2: Define the wrapper function.
The interpreter defines the wrapper()
function (in the decorator()
local scope) that takes the same arguments as the decorated function. The wrapper()
body contains the main logic of the decorator and calls the function from the non-local scope.
The wrapper()
function is not executed at this step.
python912345def wrapper():# code block# result = func()# return resultreturn wrapper
Step 3: Decorator execution ends.
The decorator()
function ends the execution and returns the wrapper()
function. The interpreter removes the decorator()
local scope but leaves the enclosed objects.
python912345678# def decorator(func):def wrapper():# code blockresult = func() # here is enclosed functionreturn result# return wrapperfunction = decorator(function)
Step 4: Reassignment
The returned wrapper()
function assigns to the decorated function: The decorated function is replaced by the other function (wrapper()
), and the previously contained function is removed.
The previous add()
function is removed but enclosed inside the returned wrapper()
function.
python9912345678910# def decorator(func):def wrapper():# code blockresult = func()return result# return wrapperfunction = wrapper# The previous `function` enclosed# inside the wrapper as `func`
Step 5: Usage
The new function is the returned wrapper()
function that takes arguments and inserts them into the enclosed function.
python912function() # is equal to returned wrapper()# The previous `function` is called inside `wrapper()`
Note
The
add
is a variable that contains a reference to the function that we defined.
python912def add(a, b): # assign the function to variable `add`return a + b
Дякуємо за ваш відгук!
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат