In this chapter, we explored decorators—both the function and class varieties. As we learned, decorators are a way to insert code to be run automatically when a function or class is defined. When a decorator is used, Python rebinds a function or class name to the callable object it returns. This hook allows us to manage functions and classes themselves, or later calls to them—by adding a layer of wrapper logic to catch later calls, we can augment both function calls and instance interfaces. As we also saw, manager functions and manual name rebinding can achieve the same effect, but decorators provide a more explicit and uniform solution.
As we also learned, class decorators can be used to manage classes themselves, rather than just their instances. Because this functionality overlaps with metaclasses—the topic of the next and final technical chapter— you’ll have to read ahead for the conclusion to this story, and that of this book at large. First, though, let’s work through the following quiz. Because this chapter was mostly focused on its examples, its quiz will ask you to modify some of its code in order to review. You can find the original versions’ code in the book’s examples package (see the preface for access pointers). If you’re pressed for time, study the modifications listed in the answers instead—programming is as much about reading code as writing it.