Python Function Decorators — A Brief Tutorial

Mark A. Brennan
The Startup
Published in
10 min readJul 28, 2019

--

Function decorators are a powerful programming tool, and Python supports them natively in the language itself through some clever syntactic sugar.

This article aims to provide a brief tutorial on the mechanics of function decorators, with some examples of their use. As a former C++ coder, I also muse a bit about decorators as one gateway (among others) to the area of meta-programming: you can argue that decorators are a higher-order feature that affords the use of design patterns at the language level.

Intro

One appeal of decorators for new Python programmers (myself included) is how their use and support in the language reveal many of Python’s functional programming aspects. This functional expressivity of Python is deeply appealing to erstwhile C++ programmers like myself.

In order to understand decorators we need to cover a few key concepts. In this article I cover:

  • Functions as First-Class Objects
  • Closures
  • Decorators
  • Examples (including a real-world use case)
  • Design Patterns and Meta-Programming

Functions as First-Class Objects:

Most Python programmers intuitively grasp this aspect of the language, but for someone with a C++ background it is slightly surprising. Functions, when passed around and/or manipulated in C++ , are done so via pointers; when…

--

--

Mark A. Brennan
The Startup

Data and ML engineer. Former C++ coder, dev manager, and product manager turned passionate Python coder and data scientist. www.linkedin.com/in/markangusbrennan