PyCon 2016 in Portland, Or
hills next to breadcrumb illustration

Monday 2:35 p.m.–3:05 p.m.

Finding closure with closures

Thomas Ballinger

Audience level:
Intermediate
Category:
Python Core (language, stdlib, etc.)

Description

What are closures all about anyway, and why is there a new keyword in Python 3? We'll look at what a closure is, their history in the Python language, what the Python 3 nonlocal keyword is about, and examine how closures are idiomatically used (and avoided) in Python.

Abstract

Since the release of Python 2.2 in 2001, all Python functions have closed over bindings in outer scopes. At the time it was a relief not to have to pass in every variable an inner function might use. Now thanks to the nonlocal keyword introduced by PEP 3104 we have rebinding closures in Python 3. With it you can simplify and clarify code, particularly some types of callbacks. I think nonlocal is pretty cool, but its reception has been tepid. We'll look at why rebinding closures are as necessary in Python as in other language, but still learn to love this new tool for clarifying our code. To do this we'll need to look at what closures are and how they're used in Python. We'll learn to recognized a variety hacks that we don't need to use anymore in python 3.