Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 149 ยท Functions

Scope: Local, Global and Nonlocal

Understand where Python looks up names with the LEGB rule, how local and global variables differ, when to use global and nonlocal, and how closures work.

Every name in Python lives somewhere. A variable you create inside a function exists only while that function runs; a variable created at the top of a file is visible to the whole file. The region of code where a name is visible is called its scope.

Scope explains a lot of puzzling behavior: why a function can read a global variable but gets an UnboundLocalError when it tries to change it, why two functions can both use a variable called total without clashing, and how an inner function can remember a value long after its outer function has finished. This lesson covers all of it, building on Functions and Return Values.

Local variables

Names you assign inside a function are local to that function. They're created fresh every time the function is called and disappear when it returns. Code outside the function can't see them.

Python Local variables stay inside

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Parameters are local variables too. name above exists only during the call.

Local scope is a feature, not a limitation. Because each function has its own private names, you can pick the clearest name for a variable without worrying that some other function somewhere already uses it.

Global variables

Names assigned at the top level of a file (outside any function or class) are global to that module. Functions can read them freely:

Python Reading a global

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading globals for constants like TAX_RATE is perfectly normal. Python's convention is to write such constants in UPPER_CASE so readers know they aren't meant to change.

The LEGB rule

When Python meets a name, it searches four scopes in order and uses the first match:

  1. Local: names assigned in the current function.
  2. Enclosing: names in any outer functions, from the nearest outward.
  3. Global: names at the top level of the module.
  4. Built-in: names Python provides everywhere, such as print, len and range.

If none of the four has the name, you get a NameError.

Python LEGB in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each function sees its own level first. Delete the line level = "local" and run again: inner now finds the enclosing one. Delete the enclosing assignment too, and it falls back to the global.

Watch out: Because built-ins come last, a local or global with the same name hides them. Writing list = [1, 2, 3] or sum = 0 works, but afterwards list(...) or sum(...) stops working in that scope. Avoid naming variables after built-ins.

Assignment makes a name local

Here's the rule that surprises most people: if a function assigns to a name anywhere in its body, that name is local for the whole function, even on lines before the assignment. Python decides this when it compiles the function, not while running it.

Python UnboundLocalError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Because of the assignment, counter inside increment is local. When Python evaluates counter + 1, that local variable has no value yet, so it raises UnboundLocalError. The global counter is never consulted.

Note that changing an object is different from assigning a name. A function can call items.append(4) on a global list without any special declaration, because append modifies the existing list; it doesn't rebind the name items.

The global statement

To rebind a global name from inside a function, declare it with global:

Python Using global

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

global works, but use it sparingly. Functions that silently change module-level state are hard to test and reason about, because their result depends on everything else that has touched that variable. Usually a cleaner design is to pass values in as arguments and return the new value, or to keep the state in an object (see Classes and Objects).

Python
def record_visit(visits: int) -> int:
    return visits + 1

visits = record_visit(visits)

Nested functions and nonlocal

A function defined inside another function can read the outer function's variables; that's the "E" in LEGB. To rebind one of them, declare it nonlocal. Without the declaration, assignment would create a new local name in the inner function, just like with globals.

Python nonlocal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

nonlocal only looks in enclosing function scopes. It never reaches the global scope, and it's a SyntaxError if no enclosing function has that name.

Closures

Look again at make_counter. By the time you call clicks(), make_counter has already returned, so its local count should be gone. Yet tick still reads and updates it. That's a closure: an inner function that keeps a reference to the variables it uses from its enclosing scope.

Each call to make_counter() creates a new count and a new tick bound to it, which is why clicks and laps count independently. You can even peek at what a closure captured:

Python Inspecting a closure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Closures are a lightweight way to bundle a little data with behavior, without writing a class. They're also the mechanism behind decorators.

The late-binding trap

Closures capture variables, not their values at the moment the function is created. A classic surprise happens with closures made in a loop:

Python Late binding in loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

By the time the first list of functions runs, the loop has finished and i is 2, so every function adds 2. A default argument is evaluated when the function is defined, which freezes the current value. You'll see this i=i idiom often. (Lambdas are covered in the next lesson.)

Scope of loops and blocks

Unlike some languages, Python has no block scope. Variables created in an if block or a for loop are ordinary locals (or globals) of the surrounding function or module, and they remain after the block ends:

Python
for n in range(3):
    squared = n * n

print(n, squared)   # 2 4 โ€” both still exist

Comprehensions are the exception: a list comprehension runs in its own scope, so its loop variable doesn't leak out.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order does Python search scopes for a name?

    The LEGB rule searches Local, then Enclosing functions, then Global, then Built-in.
  2. 2. A function contains total = total + 1, and total is a global. What happens when it runs?

    The assignment makes total local for the whole function, so reading it before it has a value raises UnboundLocalError. Add global total or, better, pass and return the value.
  3. 3. When do you need nonlocal?

    Reading an enclosing variable works without any declaration. nonlocal is needed only to assign a new value to it.
  4. 4. Which statement about closures is true?

    Closures capture variables, not snapshots. That's why closures created in a loop all see the loop variable's final value unless you bind it with a default argument.
  5. 5. After for n in range(5): pass at module level, what is n?

    Python has no block scope, so the loop variable remains and holds the last value it was given, 4.

Summary

  • Scope is where a name is visible. Names assigned in a function are local to it.
  • Python resolves names with the LEGB rule: Local, Enclosing, Global, Built-in.
  • Assigning to a name anywhere in a function makes it local for the whole function, which causes UnboundLocalError if you read it first.
  • global rebinds a module-level name; nonlocal rebinds a name in an enclosing function. Use both sparingly.
  • A closure is an inner function that remembers variables from its enclosing scope. Closures capture variables, not values, so bind loop values with a default argument.
  • Python has no block scope: loop and if variables survive the block, but comprehension variables don't leak.

Next: Lambda Functions, small anonymous functions for sorting keys and quick callbacks.