Skip to Content
Fluent Python, 2nd Edition
book

Fluent Python, 2nd Edition

by Luciano Ramalho
April 2022
Intermediate to advanced
1014 pages
23h 59m
English
O'Reilly Media, Inc.
Book available
Content preview from Fluent Python, 2nd Edition

Chapter 9. Decorators and Closures

There’s been a number of complaints about the choice of the name “decorator” for this feature. The major one is that the name is not consistent with its use in the GoF book.1 The name decorator probably owes more to its use in the compiler area—a syntax tree is walked and annotated.

PEP 318—Decorators for Functions and Methods

Function decorators let us “mark” functions in the source code to enhance their behavior in some way. This is powerful stuff, but mastering it requires understanding closures—which is what we get when functions capture variables defined outside of their bodies.

The most obscure reserved keyword in Python is nonlocal, introduced in Python 3.0. You can have a profitable life as a Python programmer without ever using it if you adhere to a strict regimen of class-centered object orientation. However, if you want to implement your own function decorators, you must understand closures, and then the need for nonlocal becomes obvious.

Aside from their application in decorators, closures are also essential for any type of programming using callbacks, and for coding in a functional style when it makes sense.

The end goal of this chapter is to explain exactly how function decorators work, from the simplest registration decorators to the rather more complicated parameterized ones. However, before we reach that goal we need to cover:

  • How Python evaluates decorator syntax

  • How Python decides whether a variable is local

  • Why closures ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Fluent Python

Fluent Python

Luciano Ramalho

Publisher Resources

ISBN: 9781492056348Errata PageSupplemental Content