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 ...
Get Fluent Python, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.