Workshop

Advanced decorators

LanguageEnglish
Audience levelAdvanced
Elevator pitch

A decorator is the cherry that goes on top of your function, giving it additional functionality… Usually!

Decorators can also go on classes and classes can also be used on decorators!

In this workshop you’ll explore advanced decorators using these two patterns.

Abstract

The decorator pattern is a functional pattern that Python developers leverage to write more modular and composable functions.

This means that your functions end up being shorter and more focused, which is good since a function should do one thing and it should do it well.

Then, you can use decorators to introduce extra useful functionality that is not part of the spec of the function. For example, you can add caching, profiling, or logging. Moreover, because you do this with decorators, you can reuse that logic for other functions.

But this is just scratching the surface. More complex scenarios might require you to write a decorator as a class or to decorate a class itself!

In this hands-on tutorial you will learn how to implement the decorator pattern in more complex scenarios. By the time we’re done, you will have implemented a number of real-world decorators as classes and decorators for classes.


Outline

Decorators recap (30’)

A brief refresher on the structure of a typical decorator (15’) plus time for attendees to write “simple” decorators (15’)

Classes as decorators (50’)

In this section I will establish a parallel between a regular decorator and a decorator written as a class, showing how to map the decorator and the wrapper function to the class’s __init__ and __call__ methods, as well as establishing a connection between the closure of the function decorator and the data attributes of the class decorator. This will take 20 - 25 minutes. The other 25 - 30 minutes will be spent on exercises.

Decorators for classes (40’)

In this section I will show how decorators for classes typically modify the class in place, for example by plugging in new methods (15’). Then, attendees will have 25’ to work on exercises.

TagsPython language features
Participant

Rodrigo Girão Serrão

Hi, I’m Rodrigo Girão Serrão from sunny Portugal 🇵🇹.

I’m a prolific Python author and speaker, with multiple books published independently and dozens of talks and tutorials given at the largest Python conferences in the world. I also blog frequently about Python and publish two Python newsletters: the weekly mathspp insider 🐍🚀 and the daily Python drops 🐍💧.

I have extensive experience teaching people from all walks of life – from kids in school, to professionals in various industries, to retirees – and there is a clear consensus that my students enjoy my clear examples, the live-coding during my lessons, and most surprisingly: my quirky sense of humour.