Python Functions · Lesson 67 of 149

Python Scope and the LEGB Rule

What you will learn

  • What scope means: where a name can be used
  • The LEGB rule: Local, Enclosing, Global, Built-in
  • Why assigning inside a function makes a new local name
  • The UnboundLocalError, and the global and nonlocal statements
  • The danger of shadowing built-ins
  • That loops and if blocks do not create a scope

1. What is scope?

The scope of a name is the part of the program where that name can be used. Names made inside a function are local to it: they exist only while the function runs, and nobody outside can see them.

def local_only():
    secret = 42
    return secret

local_only()
print(secret)
NameError: name 'secret' is not defined

Scope keeps functions independent: two functions can each use a variable called total without disturbing each other.

Quick check: can the code outside a function read a variable that was created inside it?

No. A local variable exists only inside its function, so outside code gets a NameError.

2. The LEGB rule

When Python meets a name, it looks for it in this order, and uses the first place that has it:

Letter Scope Where it is
L Local inside the current function
E Enclosing inside any function that contains the current one
G Global at the top level of the file (the module)
B Built-in Python's own names: len, print, max, ...
x = "global"

def show():
    print(x)

show()
global

Inside show, there is no local x, so Python moves outwards and finds the global x. Reading a global from inside a function works without any special word.

3. Assigning creates a local name

The rules change when you assign. A name that is assigned anywhere inside a function is local to that function (unless declared otherwise). The global of the same name is not touched:

x = "global"

def shadow():
    x = "local"
    return x

print(shadow())
print(x)
local
global

The x inside shadow is a different variable that shadows (hides) the global x. The outer one stays "global".

The UnboundLocalError

This rule leads to a famous surprise. If a function reads a name and also assigns it later, then the name is local for the whole function, including the lines before the assignment:

x = "global"

def read_then_assign():
    print(x)
    x = "local"

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

Python saw x = "local" in the function, so it decided x is local, and then the earlier print(x) found a local x with no value yet. (Older Python versions word this message as local variable 'x' referenced before assignment.)

The same happens with +=, because counter += 1 means counter = counter + 1, which assigns:

counter = 0

def bump_bad():
    counter += 1

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

4. The global statement

To assign to a global variable from inside a function, declare it with global:

counter = 0

def bump():
    global counter
    counter += 1

bump()
bump()
print(counter)
2

global counter tells Python: "the name counter in this function means the one at the top level". You can even create a new global this way:

def make():
    global created
    created = "now exists"

make()
print(created)
now exists

Use global sparingly. A function that changes a global has a hidden effect: you cannot tell from the call what it will change, and it becomes hard to test and reuse. It is almost always better to pass values in as arguments and return results:

def bump_value(counter):
    return counter + 1

counter = bump_value(counter)

Mutable globals do not need global

global is needed only to rebind a name. Changing a list in place is not rebinding, so it works without the statement:

data = []

def add_one():
    data.append(1)

add_one()
print(data)
[1]

This is still a hidden effect. It is legal, but pass the list as an argument when you can.

5. Enclosing scopes and nonlocal

A function defined inside another function can read the outer function's names (the E in LEGB):

def outer():
    msg = "outer"

    def inner():
        return msg

    return inner()

print(outer())
outer

As with globals, assigning in the inner function creates a new local. To rebind the outer function's variable, use nonlocal:

def outer():
    n = 0

    def inner():
        nonlocal n
        n += 1
        return n

    inner()
    inner()
    return n

print(outer())
2

Without nonlocal, n += 1 inside inner would raise the UnboundLocalError. nonlocal refers to the nearest enclosing function's variable, not to a global. This is the key tool behind closures (lesson 11.10).

def outer3():
    v = 1

    def inner():
        v = 2
        return v

    inner()
    return v

print(outer3())
1

Here inner assigned v without nonlocal, so it made its own local v, and outer3's v stayed 1.

6. Parameters are local

The parameters of a function are local names, created when the function is called (lesson 11.2):

y = 10

def uses_param(y):
    y += 1
    return y

print(uses_param(y))
print(y)
11
10

The outside y was passed in, but the function changed only its own y.

7. Shadowing built-ins

Built-in names such as list, len, max, sum and id are the last place Python looks. If you create a name with the same spelling, yours hides the built-in. In the function it hides it only locally:

def bad_builtin():
    list = [1, 2]
    return len(list)

print(bad_builtin())
print(list("ab"))
2
['a', 'b']

The function works, but inside it you can no longer call list(...). Worse, at the top level the damage lasts:

len = 5
len("abc")
TypeError: 'int' object is not callable

Avoid names like list, dict, set, str, sum, max, min, len, type, id, input and file. Good alternatives: items, lookup, total, biggest, kind, ident. (Restart your shell, or del len, if you shadowed one by accident.) You can see the list of built-ins with dir(builtins) after import builtins.

8. Loops and ifs do not make a scope

Python has no block scope: only functions (and classes and modules) create a scope. A variable created inside a for, while or if is still visible after the block, in the same function:

for i in range(3):
    pass
print("loop variable after:", i)

if True:
    inside_if = "visible"
print(inside_if)
loop variable after: 2
visible

This differs from some other languages. The one exception is a comprehension, which has its own scope, so its loop variable does not leak out:

sq = [k * k for k in range(3)]
print(k)
NameError: name 'k' is not defined

9. Looking at scopes

globals() and locals() give the names in the global and the local scope as dictionaries:

def show_scopes():
    a = 1
    b = 2
    return sorted(locals())

print(show_scopes())
print("x" in globals(), globals()["x"])
['a', 'b']
True global

This is mainly for exploring and debugging. Reaching into globals() to create variables is a bad habit.

10. Names resolved when the function runs

A function looks up global names at the moment it runs, not when it is defined. So a function may mention a global that is created later, as long as it exists before the call:

def lazy():
    return later_defined

later_defined = "ok"
print(lazy())
ok

This is also why functions can call each other in any order in a file, provided everything is defined before the first call that starts the chain (lesson 11.1).

Worked example: a counter, three ways

We want a counter that goes up by one each time it is used. Compare three designs.

# 1. a global variable (works, but hidden effects)
count = 0
def tick_global():
    global count
    count += 1
    return count

# 2. state passed in and returned (no hidden effects)
def tick_value(count):
    return count + 1

# 3. a closure: the state lives in an enclosing scope
def make_counter():
    n = 0
    def tick():
        nonlocal n
        n += 1
        return n
    return tick

print(tick_global(), tick_global())

c = 0
c = tick_value(c)
c = tick_value(c)
print(c)

a = make_counter()
b = make_counter()
print(a(), a(), a(), b())
1 2
2
1 2 3 1
Design State lives in Drawback
global the module any code can change it; one counter only
value in, value out the caller's variable the caller must keep passing it
closure the enclosing scope of make_counter slightly more advanced

Each call to make_counter() creates a separate n, so a and b count independently. This is a preview of closures, lesson 11.10.

Common mistakes

  • Assigning to a global inside a function without global, which creates a local instead (or raises UnboundLocalError).
  • Reading a name and assigning it later in the same function.
  • Using global everywhere instead of arguments and return values.
  • Naming a variable list, sum, max, len, type or input.
  • Expecting a loop or if to have its own scope.
  • Forgetting nonlocal when an inner function must change an outer variable.

Key takeaways

  • Python looks up a name in this order: Local, Enclosing, Global, Built-in (LEGB).
  • A name assigned anywhere in a function is local to it; reading a name that is also assigned later gives an UnboundLocalError.
  • global name lets a function rebind a global; nonlocal name lets an inner function rebind an enclosing variable.
  • Changing a mutable object in place does not need either statement, but it is still a hidden effect.
  • Do not shadow built-ins; only functions (and classes and modules), and comprehensions, create scopes, not loops or if.

Practice

1. What does this print? x = 1, def f(): x = 2, then f() and print(x).

Show answer

1. The x = 2 inside f made a new local variable and left the global alone.

2. Why does def f(): n += 1 fail when n = 0 is at the top level?

Show answer

n += 1 assigns, so n is local to f, and the local n has no value when it is read: UnboundLocalError. Add global n (or better, pass the value in and return the result).

3. Which statement lets an inner function change a variable of the function around it?

Show answer

nonlocal name.

4. What goes wrong if you write sum = 0 at the top of your program?

Show answer

It hides the built-in sum, so a later call like sum([1, 2]) fails with TypeError: 'int' object is not callable. Use another name such as total.

5. After for i in range(3): pass, does print(i) work?

Show answer

Yes, it prints 2. A loop does not create its own scope.

6. Rewrite a function that uses global total so that it needs no global.

Show answer

Take the value as a parameter and return the new value: def add(total, n): return total + n, then total = add(total, 5).