Skip to content
FollowtheDamnCode

Scope

Local and global names, and where Python looks them up.

4 minute read

Big idea

Scope is where a name can be seen. Names created inside a function are local — they exist only while that function runs. Names created at the top level of the file are global.

Local variables

A local variable vanishes after the call
def make_message():
    message = "made inside"
    print(message)

make_message()
print("Outside, message is", "message" in dir())
output
made inside
Outside, message is False

Run and edit it in the app.

(dir() lists the names that exist right here — message isn't one of them.) Each call gets a fresh set of local names, and they're thrown away when the function returns.

Same name, different variables

A local variable can have the same name as a global one. Inside the function, the local one wins, and the global is untouched:

Predict: which x?
x = "global"

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

show()
print(x)
What does it print? Show the answer
local
global

Run and edit it in the app.

Reading globals is fine

A function can read a global name:

TAX_RATE = 0.18

def with_tax(price):
    return price * (1 + TAX_RATE)

But assigning to a name anywhere in a function makes it local for the whole function:

Fix the bug: count should become 1
count = 0

def increment():
    count = count + 1

increment()
print(count)
output
1

Run and edit it in the app.

count = count + 1 makes count local, so reading it on the right is an UnboundLocalError — the local has no value yet. You could write global count at the top of the function, but there's a cleaner fix: pass the value in and return the result.

def increment(count):
    return count + 1

count = increment(count)

The LEGB rule

When Python looks up a name, it searches four places in order:

Where Python looks for a name, innermost first

The first place that has the name wins. That's also why naming a variable list or print is a bad idea — your global hides the built-in.

def f(): y = 5 — after calling f(), can the main program print(y)?

Watch it

Think of it like

Notes written on a whiteboard in a meeting room. When the meeting (the function call) ends, the board is wiped. Notes pinned on the office noticeboard (globals) stay — but it's polite not to scribble on them from inside a meeting.

Key terms

  • Scope — The region of code where a name is visible.
  • Local variable — Created inside a function; exists only during the call.
  • Global variable — Created at the top level of a file.

Check yourself

Where does a variable created inside a function exist?

In what order does Python look up a name?

What's the cleanest way for a function to change a counter?