liveBook · Manning

Scope

As explained in Python Workout: 50 ten-minute exercises

A local variable is a variable whose scope is limited to the function in which it is defined.

Scope determines where names are visible and how Python resolves them. Inside a function, Python searches Local, Enclosing function, Global, then Built-ins (LEGB), stopping at the first match. section 6.5

Use these distinctions when tracing a name:

  • Indentation organizes Python code but does not itself create variable scope; functions do. section 6.5

Closures preserve enclosing state

A nested function can retain access to an enclosing variable after the outer function returns. With nonlocal call_counter, each call updates that retained state, producing counts from 1 through 9.

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines LEGB and demonstrates globals, closures, global, and nonlocal, without descending into interpreter implementation.
Examples
Uses shadowed x values, a global sum collision, a closure multiplier, and a nonlocal call counter.
What it assumes
Assumes familiarity with functions and variables while clarifying Python's scope rules from their practical effects.
What you can do after
Diagnose name-resolution surprises and choose global or nonlocal when deliberately updating outer state.
How it connects
Connects scope with functions, closures, nested functions, global variables, built-ins, and name shadowing.

Also explained in

Compare how 21 books explain scope →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.