TExcelTAD
Home › Python › Python Scope

Python Scope

The scope of a variable is the part of the program where that name can be seen and used. Scope rules explain why a variable created inside a function "disappears" afterwards, and why changing a global from inside a function needs a special keyword.

Local scope

A variable assigned inside a function is local to that function. It is created when the function runs and forgotten when it returns:

python · try it yourself
def make_greeting():
    message = "Hello from inside"
    return message

print(make_greeting())

try:
    print(message)
except NameError as err:
    print("Error:", err)
Hello from inside
Error: name 'message' is not defined

Every call gets fresh local variables, so two functions can use the same local name without interfering.

Global scope

A variable created at the top level of a file is global. Functions can read it:

python · try it yourself
TAX_RATE = 0.08

def price_with_tax(price):
    return round(price * (1 + TAX_RATE), 2)

print(price_with_tax(50))
54.0

Assigning creates a local

Here is the rule that surprises people: if a function assigns to a name anywhere in its body, that name is local throughout the whole function — even if a global with the same name exists:

python · try it yourself
counter = 0

def increment_wrong():
    counter = 1          # creates a NEW local variable
    return counter

increment_wrong()
print(counter)           # the global is unchanged

def increment_broken():
    try:
        counter += 1     # reads the local before it exists
    except UnboundLocalError as err:
        print(type(err).__name__)

increment_broken()
0
UnboundLocalError

The global keyword

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

python · try it yourself
visits = 0

def record_visit():
    global visits
    visits += 1

record_visit()
record_visit()
print(visits)
2

Tip: Use global sparingly. Functions that read their inputs from parameters and hand back results with return are much easier to test and reuse.

Enclosing scope and nonlocal

When a function is defined inside another function, the inner one can read the outer one's variables. To rebind them, use nonlocal:

python · try it yourself
def make_counter():
    count = 0
    def step():
        nonlocal count
        count += 1
        return count
    return step

tick = make_counter()
print(tick(), tick(), tick())

other = make_counter()     # an independent counter
print(other())
1 2 3
1

Each call of make_counter creates a new count, and the returned step function keeps access to it — a closure.

The LEGB rule

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

Order Scope Contains
L Local names assigned in the current function
E Enclosing names in any outer function(s)
G Global names at the top level of the module
B Built-in print, len, range, …
python · try it yourself
x = "global"

def outer():
    x = "enclosing"
    def inner():
        x = "local"
        print("inner sees:", x)
    inner()
    print("outer sees:", x)

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

Don't shadow built-ins

Because built-ins are searched last, a global or local with the same name hides them:

python · try it yourself
list = [1, 2, 3]          # hides the built-in list type
try:
    list("abc")
except TypeError as err:
    print("Error:", err)
del list                   # remove our name; the built-in is visible again
print(list("abc"))
Error: 'list' object is not callable
['a', 'b', 'c']

Avoid naming variables list, dict, str, sum, max, id or input.

Note: Loops and if blocks do not create a new scope in Python. A variable assigned inside a for loop is still available after the loop ends.

Test yourself

Which keyword lets a function rebind a variable defined at module level?

  1. nonlocal
  2. global
  3. outer
  4. static

In what order does Python search scopes for a name?

  1. Global, Local, Built-in, Enclosing
  2. Local, Enclosing, Global, Built-in
  3. Built-in, Global, Enclosing, Local
  4. Local, Global, Enclosing, Built-in

Does a for loop create its own variable scope?

  1. Yes, always
  2. No, loop variables live in the surrounding scope
  3. Only inside functions
  4. Only for range()