A Taxonomy of Decorators: A-E

By Andy Fundinger

Elevator Pitch

Since their addition in Python 2.4, Decorators have become an established part of the Python language and many of our development projects. This talk will look at the purpose, implementation, and pitfalls of five types of decorators, from the Argument changing decorator to the Execution decorator.

Description

This talk will briefly go over the various decorator syntaxes before breaking up the common usages of decorators into 5 categories. Effectively, these are design patterns for decorators. The usages to be considered are:

  • A - Argument Changing Decorators – Decorators that change a function’s arguments, including changing its signature
  • B - Binding Decorators – Decorators that implement the Descriptor Protocol, such as the builtins: @property, @classmethod, and @staticmethod
  • C - Control Flow Decorators – Decorators that change when or whether the function will be called, such as @retry or @lrucache
  • D - Descriptive Decorators – Decorators that do not change the function, but create a reference to it elsewhere, like pytest.mark and flask.app.route
  • E - Execution Decorators – Decorators that retrieve source code and/or AST and alter it.

Notes

This talk extends from the normal decorator talk to discuss not how to write them, which is assumed, but rather what different sorts of decorators exist and what the upsides and downsides are by type.