Introduction to Decorators¶
In Python, a decorator is a callable object used to modify an original function, method, or class, and if necessary, it must still meet certain basic requirements. But in any case, it is passed an original object and returns a modified object that is then bound to the name in the definition.
modified = Decorator(original)
The well known decorator syntax using @
as a keyword is pure
syntactic sugar. This so-called pie syntax or pie notation
@Decorator
def function():
pass # Some code ...
is a functionally equivalent abbreviation for
def function():
pass # Some code ...
function = Decorator(function) # Same for function, method or class
in which case the modified object again gets the same name as the original object. Essentially, functions, methods or classes are added functionality at definition time and are therefore a construct at a higher meta-level.
Since the decorator is defined as an arbitrary callable object, it can be implemented in Python using either of these techniques:
- Closures
Functions with extended environment, or
- Callable objects
Classes implementing a
__call__
method.
Functionally, both techniques are absolutely equivalent, i.e. it is a matter of personal taste which one to choose. For getting started with decorators and for smaller implementations closures seem to be the first choice, with regard to the use of additional parameters, e.g. for the configuration of decorators, move callable objects into focus.
- Comment:
According to standard Python naming conventions, decorators based on closures should follow the snake_case convention for function names and those based on classes should follow the UpperCamelCase convention for class names.
Thus, the symbolic Decorator
is used below as an example
representative of an arbitrary class-based decorator.
© Copyright 2020-, Martin Abel, eVation. All Rights Reserved. |