Variable Scope

Which name a piece of code can see, the four places Python looks, and why assigning inside a function does not change the outside.

Overview

Which name a piece of code can see, the four places Python looks, and why assigning inside a function does not change the outside.

In this guide
  1. The four places
  2. Reading is easy, assigning is the trap
  3. The rule that catches everyone
  4. global and nonlocal
  5. Mutating is not assigning
  6. Why the rule exists
  7. Closures, and why they are useful
  8. Globals, and when they stop being harmless
  9. Shadowing builtins
  10. Watching the four scopes resolve
  11. Comprehensions have their own scope, loops do not
  12. Where scope shows up in practice
  13. Why there is no block scope
  14. Questions people ask about Variable Scope
  15. Variable Scope: recap in one screen
  16. Scope says who can see a name, not who can see it at the same time

scope.py

scope.py Python 3
Output

                    

legb.py

legb.py Python 3
Output

                    

Worth knowing

Python looks in four places, in order: Local, Enclosing, Global, Builtin.
Reading an outer name works. Assigning creates a local one instead.
One assignment anywhere makes the name local for the whole function - which is why reading it earlier raises UnboundLocalError.
global rebinds a module name; nonlocal rebinds the enclosing function's.

Variable Scope: A Practical Guide

When Python meets a name, it looks in four places in a fixed order. Local, enclosing, global, builtin. And stops at the first one that has it. Almost each scope surprise comes from one rule about set.

The four places

LEGB is the order:

  • Local — names assigned in the current function
  • Enclosing — names in a function that wraps this one
  • Global — names at module level
  • Builtin — len, print, range and friends

The first match wins. This is why naming a variable list or sum shadows the builtin for the rest of that scope. It is legal, and it will confuse you later.

Scope is the set of rules that decides which variable a name refers to. When you write x inside a function, Python does not search every variable in the program. It checks four places, in order, and uses the first match. If none of the four has that name, you get a NameError.

Most of the time scope is invisible. You assign a variable inside a function, and it stays local. You read a module-level constant, and it resolves through the global scope. The rules only become noticeable when they surprise you, and the surprise almost always involves assignment.

Reading a global variable from inside a function works without any special syntax. But assigning to a name inside a function creates a local variable, even if a global with the same name already exists. That means a function can read a global on one line and accidentally shadow it on the next. The global keyword exists to override this behavior, telling Python that an assignment inside the function should update the module-level name instead of creating a new local one. The nonlocal keyword does the same for a name in an enclosing function.

This page covers the four LEGB scopes, why assignment creates a local, how global and nonlocal change that behavior, and the common traps that catch beginners off guard.

Reading is easy, assigning is the trap

A function can read an outer name without ceremony:

x = "global"
def show():
    print(x)  # fine

But assigning to that name inside the function doesn't change the outer one. It creates a new local name that happens to be spelled the same. It disappears when the function returns.

The rule that catches everyone

If a name is assigned anywhere in a function, it's local for the entire function. Including lines that run before the set.

def broken():
    print(x)      # UnboundLocalError
    x = "too late"

That print looks like it should read the global. It would have, if the line below it didn't exist. Python decides local-or-not when it compiles the function, not while running it. The error message. "local variable referenced before set". Is precise once you know this, and baffling before.

global and nonlocal

To rebind rather than shadow, say so:

def bump():
    global count
    count += 1

global reaches module level. nonlocal reaches the nearest enclosing function. This Is what makes closures able to keep state:

def counter():
    n = 0
    def step():
        nonlocal n
        n += 1

Both are worth knowing and neither is worth reaching for often. A function that rebinds globals is a function whose action depends on when you call it. This Is just the kind of thing that makes bugs hard to find. Returning a value is nearly always better.

Mutating is not assigning

One clarification that resolves a lot of confusion: items.append(1) isn't an set. It mutates the object the name already points at. It affects the outer list without needing global. items = [1] is an set. Creates a local. The gap is the object versus the name.

Why the rule exists

Deciding local-or-not at compile time looks like an odd choice until you consider the option. If Python worked out scope while running, then whether a name was local could depend on which branch had ran, and the same line could mean two different things on two different runs. Instead the compiler scans the whole function body once: if a name is assigned anywhere in it, that name is local all over in it.

That single rule shows the UnboundLocalError that catches everyone. The read on line one is a read of a local variable. Line five assigns to it, and the local has no value yet. The error message is precise. It just shows a choice made before the function ran.

Closures, and why they are useful

A function defined inside another function can see the enclosing function's variables, and it keeps seeing them after the outer function has returned. That combination - an inner function plus the variables it captured - is a closure, and it's how a function can carry state without a class or a global.

The counter on this page is the small version. The pattern scales to configuration: a function that builds and returns another function with some settings already baked in. make_formatter(currency="GBP") returns a thing you can call many times without repeating the currency.

nonlocal exists because assigning inside the inner function would or else create a new local there, just as it would at module level. It says "this name belongs to the function that wraps me", and it's the only way to update captured state rather than merely read it.

Globals, and when they stop being harmless

Reading a module-level constant from inside a function is plain and fine - that is what constants are for. Writing to a module-level name from inside a function is where trouble starts, because the function's action now depends on what ran before it, and testing it in alone stops being possible.

The hands-on test is whether calling the function twice with the same args gives the same answer. If a global statement means it doesn't, the state probably wants to be a param, a return value, or an field on an object - all three of which make the dependency visible in the signature rather than buried in the body.

Shadowing builtins

list, dict, set, id, type, sum, input and max are all plain names that happen to be defined in the builtin scope, and assigning to any of them inside your code hides the first for the rest of that scope. It's legal and it makes confusing failures later, often when a thing calls list(x) and gets a TypeError about your list not being callable.

Watching the four scopes resolve

LEGB is easier to trust once you've seen it choose:

x = "global"

def outer():
    x = "enclosing"

    def inner():
        print("inner sees:", x)

    inner()

outer()
print("module sees:", x)
inner sees: enclosing
module sees: global

inner never assigns x, so it looks outward: not local, so enclosing — and it stops there, at outer's x, without ever reaching the module-level one. The module's x is untouched, because outer's set created a name in outer rather than changing the global.

Now the version that fails:

def broken():
    print(x)
    x = "too late"

broken()
UnboundLocalError: cannot access local variable 'x' where it is not associated
with a value

There's a just right good global x, and the print doesn't reach it. The set on the line *below* made x local for the whole function, so the print is reading a local that hasn't been given a value yet.

The wording of that error changed in Python 3.11. Older versions say "local variable 'x' referenced before set". Both show the same thing, and the newer one is clearer about it.

Comprehensions have their own scope, loops do not

Two things that look similar and differ. This Shows a family of small surprises.

A for loop does not create a scope. The loop variable is an plain local, it lives after the loop ends. It overwrites any of it of the same name. This is why for i in range(3) leaves i set to 2 afterwards, and why reusing a name in nested loops silently shadows.

A comprehension does create one. Its loop variable lives only inside it, doesn't leak, and doesn't clobber a name of the same spelling outside. This changed in Python 3 in detail because the leaking was a common source of bugs.

The consequence worth remembering is that a comprehension can read enclosing names but can't see a class body's names. A comprehension written right in a class body that refers to another class field raises NameError, because the class body isn't a function scope and the comprehension's scope skips straight past it to the module. It's the one truly strange corner of Python's scoping, and the fix is to find the value outside the class or pass it in through the iterable.

Where scope shows up in practice

The rules are short. The situations where they bite are worth naming.

A function that "doesn't update" a counter. Assigning to a module-level name inside a function creates a local instead. The function appears to run and the value never changes. global fixes it and is often the wrong fix — returning the new value and assigning at the call site keeps the dependency visible.

A callback that captured the wrong value. Functions built in a loop capture the *variable*, not its value. So They all see the final one. Binding it as a default arg — lambda i=i: ... — captures at meaning time. This is the same late-binding action that makes closures handy, seen from the wrong side.

A shadowed builtin. Naming a variable list, dict, sum, id or input hides the builtin for the rest of that scope. The failure comes later, often as TypeError: 'list' object isn't callable, at a line that looks correct.

A name that only exists at times. Assigning inside an if and reading after it works when the branch ran and raises UnboundLocalError when it did not. Reset before the branch.

All four are the same rule seen from different angles: set decides where a name lives, and it decides it for the whole function.

Why there is no block scope

Coming from C, Java or JavaScript, the most surprising rule is that an if or a for doesn't create a scope. A name assigned inside one is visible after it, and the loop variable outlives the loop.

This is deliberate, and the thinking is the same as all over else in the language: functions are the unit of encapsulation, and adding a second, finer kind of scope would mean two sets of rules for readers to hold. A function body is one namespace, and where in that body a name was first assigned doesn't change what it refers to.

It has hands-on consequences worth using rather than fighting. A value found inside an if is available afterwards. So The common pattern of declaring a variable before a branch purely so it exists later is unneeded — assign it in both branches instead. A loop can leave its last value behind on purpose, which is at times the neat way to say "the last item that matched".

It also has one real hazard: a name assigned only inside a branch that didn't run doesn't exist, and reading it raises UnboundLocalError. The compiler knows the name is local. So It doesn't fall back to a global of the same spelling. Resetting before the branch, or assigning on each path, is the fix — and the error is at least loud rather than silently reading a thing from an outer scope.

The one exception, comprehensions, exists just because the leaking there was a genuine problem rather than a convenience.

Questions people ask about Variable Scope

Does an if or a for block create a scope? No. Only functions, classes, modules and comprehensions do.

Can I read a global without declaring it? Yes. global is only needed to *assign* to one.

What is the difference between global and nonlocal? global reaches module level. nonlocal reaches the nearest enclosing function. nonlocal fails if there's no such name.

Why does items.append(1) work without global? Because it mutates the object rather than rebinding the name. Only set is affected.

Does a class body count as an enclosing scope? No, and this is the exception that surprises people — methods don't see class-level names without self or the class name.

Can I list what is in scope? locals() and globals() return dicts of the current names. This Is at times handy for debugging.

Is shadowing a builtin ever fine? In a two-line function where it's obvious, it does no harm. As a habit it costs more than the shorter name saves.

Does del x drop a name from scope? It unbinds it, so a later read raises NameError or UnboundLocalError. It doesn't reach into an outer scope.

Why can a method not see class fields right? Because a class body isn't an enclosing scope for its methods. Reach them through self. or the class name.

What scope does a lambda have? The same as any function: its own local scope, with the enclosing one visible. That is why the loop-capture trap applies to lambdas just as it does to def.

Variable Scope: recap in one screen

  • Names resolve local, enclosing, global, builtin — first match wins.
  • If a name is assigned anywhere in a function it's local all over in that function, including lines above the set.
  • global and nonlocal rebind rather than shadow, and both are often a sign that a return value would be better.
  • Mutating isn't assigning: items.append(x) needs no declaration, items = [x] creates a local.
  • A for loop shares the enclosing scope. A comprehension has its own.

Scope says who can see a name, not who can see it at the same time

All above assumes one thread of run. Add a second and each rule still holds — a call still gets its own local namespace, global still rebinds at module level — but a question appears that scope can't answer. Two threads running the same function have separate locals, and *share* each global, along with each mutable object those locals happen to point at.

That sharing is where the hard bugs live. counter += 1 on a module-level int is a read, an add and a write. The other thread can be scheduled in either gap.

Check yourself

0 of 3

Answer without scrolling back up.

  1. What order does Python search for a name?

  2. Why does reading `x` before `x = 1` inside a function raise?

  3. `items.append(1)` inside a function affects the outer list. Why no `global`?

Cheat sheet

Variable Scope

Trace how Python resolves a name through local, enclosing, global and built-in scopes, and see why assigning inside a function creates a new local.

PYTHON · vizlearn.in/python/variable_scope.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.