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.

  1. def foo():
  2. # do something
  3.  
  4. def decorator(func):
  5. # manipulate func
  6. return func
  7.  
  8. foo = decorator(foo) # Manually decorate
  9.  
  10. @decorator
  11. def bar():
  12. # Do something
  13. # 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.