Python Quest

Track 12 · Lesson 4 of 12

Closures

Nested functions that remember variables from where they were created: function factories, private state with nonlocal and the late-binding trap.

About 40 minIntermediate4 exercises

You will be able to

  • Define a function inside another function and return it
  • Explain what a closure captures and why the values survive after the outer function returns
  • Use nonlocal to update captured state, and know when mutation needs no nonlocal
  • Fix the late-binding bug when creating functions in a loop
  • Choose between a closure and a small class

Included with a Formula Quest membership

It has 4 graded exercises with feedback, hints and solutions. Python Quest is included in Formula Quest memberships that cover Python; membership and billing are managed on Formula Quest.

View Formula Quest memberships

Tracks 1 and 2, the first lesson of every track, the playground and the dataset library are free.