Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

VIII. Advanced Topics > 38. Decorators - Pg. 985

CHAPTER 38 Decorators In the advanced class topics chapter of this book (Chapter 31), we met static and class methods and took a quick look at the @ decorator syntax Python offers for declaring them. We also met function decorators briefly in the prior chapter (Chapter 37), while exploring the property built-in's ability to serve as a decorator, and in Chapter 28 while studying the notion of abstract superclasses. This chapter picks up where the previous decorator coverage left off. Here, we'll dig deeper into the inner workings of decorators and study more advanced ways to code new decorators ourselves. As we'll see, many of the concepts we studied in earlier chapters, such as 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 under- standing 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 are somewhat larger than most 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, much of the code we'll write here may be used as general-purpose tools in your day-to-day programs. What's a Decorator? Decoration is a way to specify management code for functions and classes. Decorators themselves take the form of callable objects (e.g., functions) that process other callable objects. As we saw earlier in this book, Python decorators come in two related flavors: · Function decorators do name rebinding at function definition time, providing a layer of logic that can manage functions and methods, or later calls to them. · Class decorators do name rebinding at class definition time, providing a layer of logic that can manage classes, or the instances created by calling them later. 985