Decorators
The Python language provides a simple yet powerful syntax called ‘decorators’.A decorator is a function or a class that wraps (or decorates) a functionor a method. The ‘decorated’ function or method will replace the original‘undecorated’ function or method. Because functions are first-class objectsin Python, this can be done ‘manually’, but using the @decorator syntax isclearer and thus preferred.
- def foo():
- # do something
- def decorator(func):
- # manipulate func
- return func
- foo = decorator(foo) # Manually decorate
- @decorator
- def bar():
- # Do something
- # bar() is decorated
This mechanism is useful for separating concerns and avoidingexternal unrelated logic ‘polluting’ the core logic of the functionor method. A good example of a piece of functionality that is better handledwith decoration is memoization or caching: you want to store the results of anexpensive function in a table and use them directly instead of recomputingthem when they have already been computed. This is clearly not partof the function logic.