liveBook · Manning

Scope

As explained in Python Workout, Second Edition

A scope is the region of Python code in which a name can be resolved according to the language's name-lookup rules.

Scope determines where Python can resolve a name. During a function call, Python searches Local, Enclosing function, Global, and Built-ins—the LEGB order—and stops at the first match. Outside functions, only global and built-in namespaces participate; indentation and loops do not create scopes. section 7.5

Use these distinctions when reading or debugging name resolution:

  • An assignment inside a function normally creates or updates a local name, leaving a same-named global unchanged. section 7.5
  • The global statement makes an assignment target the global name instead of the function-local name. section 7.5
  • Built-in names such as int are searched after globals, so rebinding a built-in such as sum can make later calls fail. section 7.5
  • An inner function can read an enclosing function's local names; nonlocal permits it to update an enclosing binding. section 7.5 section 7.11

A closure preserves enclosing state

def foo(): call_counter = 0 def bar(y): nonlocal call_counter call_counter += 1 return f'y = {y}, call_counter = {call_counter}' return bar b = foo() print(b(10)) # y = 10, call_counter = 1 print(b(20)) # y = 20, call_counter = 2 The returned function retains access to call_counter from foo's enclosing scope, even after foo returns. section 7.5 section 7.11

x = 100

def foo():
    x = 200
    print(x)

print(x)
foo()
print(x)

Compare inner and outer x values to see local shadowing without global mutation. section 7.5

How Python Workout, Second Edition covers it

How deep it goes
Defines LEGB and works through local, global, built-in, enclosing, closure, and nonlocal behavior with executable examples.
Examples
Uses shadowed x and sum names, global reassignment, nested multipliers, call counters, and password-generating closures.
What it assumes
Assumes familiarity with functions and extends that foundation to nested functions, namespaces, and closures.
What you can do after
Diagnose name-resolution mistakes involving local shadowing, built-in rebinding, global assignment, and retained closure state.
How it connects
Connects functions, nested functions, closures, global variables, built-in namespaces, 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, Second Edition. The section links point to the parts of the book it draws on.