Skip to Main Content
Fluent Python
book

Fluent Python

by Luciano Ramalho
August 2015
Intermediate content levelIntermediate
790 pages
18h 48m
English
O'Reilly Media, Inc.
Content preview from Fluent Python

Chapter 7. Function 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.

One of the newest reserved keywords 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 know closures inside out, and then the need for nonlocal becomes obvious.

Aside from their application in decorators, closures are also essential for effective asynchronous programming with callbacks, and for coding in a functional style whenever 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 exist and how they work

  • What problem is solved ...

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, 2nd Edition

Fluent Python, 2nd Edition

Luciano Ramalho

Publisher Resources

ISBN: 9781491946237Errata Page