Chapter 39. Decorators
In Chapter 32’s survey of class odds and ends, we met properties and static and class methods, took a quick look at the @ decorator syntax Python offers for declaring them, and previewed decorator coding techniques. We also met function decorators briefly while exploring the property built-in in Chapter 38, in the context of abstract superclasses in Chapter 29, and in capsule form in Chapter 19.
This chapter picks up where all this previous decorator coverage left off. Here, we’ll dig deeper into the mechanics of decorators and study more ways to code new decorators ourselves with tools like arguments and nesting. As we’ll find, other concepts we studied earlier—especially state retention—show up regularly in decorators.
This is a somewhat advanced topic, and decorator construction tends to be of more interest to tool builders than to application programmers. Still, given that decorators are becoming increasingly common in popular Python frameworks, a basic understanding can help demystify their role, even if you’re just a decorator user.
Besides covering decorator construction details, this chapter serves as a more realistic case study of Python in action. Because its examples grow larger than many of the others we’ve seen in this book, they better illustrate how code comes together into more complete systems and tools. As an extra perk, some of the code we’ll write here may be used as general-purpose tools in your day-to-day programs.
What’s a Decorator? ...
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.
Read now
Unlock full access