Tag: decorator function

Python- Decorator Stacking

Python allows to apply multiple decorators to callable object.

The decorator function is called based on the order or the sequence it has been listed.

Decorator can also use there own arguments. In the below example @log decorator a parameter is passed with value ‘log sample’.

Log decorator has 2 wrapper functions. Outer function accepts the reference or pointer to the decorated fucntion and an internal function holds arguments that are passed to the decorated fucntion.

The decorated function is called from the internal wrapper function along with the parameters.

The parameter passed to the decorator is also assessible in the decorator function.

Coming back to Decorator stacking. The below example is used to decorate the fucntion with multiple decorators. Here log and executiontime are decorator function and stacked on the decorated function i.e. sample

Python- Decorator functions

Decorators are very useful for refactoring or debugging the code.

Decorators are used to but not limited to do the following –

  • validate the arguments
  • modiy the arguments
  • modify the returned objects
  • message logging
  • caching

See below code snippet calls the log function to the decorator method which returns the log function.

Other way to perform the same is by decorating the method with @decorator method which widely in Python

The above example can be rewritten with following code snippet. Here the calling function is decorated with log function which returns

Arguments passed to the deocrated function can also be made available to the decorator function using *args and **kwargs

See below example for same. Here the decorator calls the decorated function and prints the same. This way you can log the execution of decorated function. Log the time the parameters, output and time taken to execute the fucntion.

This way decorator function can be made global.