6.1. Decorator About
Decorator is an object, which takes another object as it's argument
Since Python 2.4: PEP 318 -- Decorators for Functions and Methods
Since Python 3.9: PEP 614 -- Relaxing Grammar Restrictions On Decorators
Decorator can do things before call
Decorator can do things after call
Decorator can modify arguments
Decorator can modify returned value
Decorator can avoid calling
Decorator can modify globals
Decorator can add or change metadata
Decorator is an object (such as function, method or class) that modifies the behavior of another object. It takes a decorated object as input and returns a modified version of that object. Decorators are a powerful feature that allows you to add functionality to an object without modifying its source code.
6.1.1. Syntax
func
is a reference to function which is being decoratedargs
arbitrary number of positional argumentskwargs
arbitrary number of keyword argumentsBy calling
func(*args, **kwargs)
you actually run original (wrapped) function with it's original arguments
Decorators are defined using the "@" symbol followed by the name of the decorator. When a function is decorated, the decorator is called with the original object as its argument. The decorator can then modify the behavior of the original object by adding new functionality or modifying its existing behavior.
Here is an example of a simple decorator that adds an additional behavior to a function:
>>> def mydecorator(func):
... def wrapper():
... print('before')
... result = func() # call the original function
... print('after')
... return result
... return wrapper
>>>
>>> @mydecorator
... def myfunction():
... print('This is my function.')
>>>
>>> myfunction()
before
This is my function.
after
In this example, the mydecorator
function takes a function as input
and returns a new function wrapper
that prints a trext before and
after calling the original function. The @mydecorator
syntax is used
to apply the decorator to the myfunction
function. When myfunction
is called, it will now print "before", execute its original code, and then
print "after".
6.1.2. Decoration
Syntax:
>>> @mydecorator
... def myfunction(*args, **kwargs):
... ...
Is equivalent to:
>>> myfunction = mydecorator(myfunction)