1.2.31Introduction to Programming (Python)

global and nonlocal keywords

1,508 words7 min readdifficulty · medium

WHY do these keywords exist?

This rule is the WHOLE reason global/nonlocal exist. Let's see WHY it bites you.


The scope ladder (LEGB)

Name lookup for reading goes: Local → Enclosing → Global → Built-in (LEGB).

  • global = "skip straight to the G level and bind there."
  • nonlocal = "bind to the nearest E (enclosing function) level — not local, not global."
Figure — global and nonlocal keywords

global — WHAT, WHY, HOW


nonlocal — WHAT, WHY, HOW


Forecast-then-Verify

Recall Predict the output BEFORE reading the answer
x = "global"
def outer():
    x = "enclosing"
    def inner():
        nonlocal x
        x = "changed"
    inner()
    print(x)
outer()
print(x)

Answer: prints changed then global. Why? nonlocal x binds inner's assignment to outer's x, changing it to "changed". The module-level x is untouched, so it stays "global".


Flashcards

What is the default scope of a name that is assigned inside a function?
Local to that function, for the entire function body (decided at compile time).
What error do you get reading a name before assigning it in the same function?
UnboundLocalError.
What does global x do?
Makes x refer to (and rebind) the module-level variable, not a local one.
What does nonlocal x do?
Binds x to the nearest enclosing function scope (not global) and lets you rebind it.
Do you need global/nonlocal just to READ an outer variable?
No — reading climbs LEGB automatically; you only need them to rebind/assign.
Do you need global to do mylist.append(5) on a global list?
No — that mutates the object, it doesn't rebind the name.
LEGB stands for?
Local, Enclosing, Global, Built-in (order of name lookup).
When nonlocal fails to find the variable, what happens?
SyntaxError — there must already be a binding in an enclosing function scope.
Difference between global and nonlocal targets?
global → module top level; nonlocal → nearest enclosing function.

Recall Feynman: explain to a 12-year-old

Imagine a house with rooms inside rooms. Each room can have its own toy box. Normally, if you put a toy in a box while standing in a room, you make a new box in that room. global says: "Don't make a new box — use the BIG box in the front hall, the one everyone shares." nonlocal says: "Use the box in the room just outside this one, not the front-hall one." If you only want to look at a toy from an outer box, you don't need to say anything — you can always peek outward.


Connections

  • Scope and LEGB rule
  • Functions in Python
  • Closures
  • Mutable vs Immutable objects
  • UnboundLocalError
  • Pure functions and side effects

Concept Map

makes name

reading needs

assign before value

fixed by

binds at

Local Enclosing Global Builtin

binds at

used inside

assign rebinds

assign rebinds

needs neither

Assignment rule

Local by default

LEGB lookup

UnboundLocalError

global keyword

Global module level

nonlocal keyword

Enclosing function level

Nested function closure

Outer variable changed

Pure reading or mutating

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, Python me ek simple but tricky rule hai: jab bhi tum function ke andar kisi naam ko = se assign karte ho, Python uss naam ko us function ka local maan leta hai — chahe wahi naam bahar bhi defined ho. Isi wajah se count = count + 1 jaisa code UnboundLocalError deta hai, kyunki Python ne pehle hi decide kar liya ki count local hai, aur local count ki abhi koi value hai hi nahi.

Yahin global aur nonlocal kaam aate hain. global x bolta hai "is function me x matlab module ke top wala x, aur main usi ko badal raha hoon." nonlocal x bolta hai "is nested function me x matlab thik bahar wale (enclosing) function ka x, global wala nahi." Yaad rakho: global = ground floor (module), nonlocal = next door (bahar wala function). Ye dono sirf tab chahiye jab tum rebind/assign kar rahe ho — sirf padhne ke liye kuch nahi chahiye, ladder apne aap outward dekh leti hai.

Closures me nonlocal ka magic dikhta hai: make_counter banao, andar n = 0, aur step har baar nonlocal n se n += 1 kare — to counter 1,2,3 yaad rakhta hai. Yahan global use karte to fail ho jata kyunki n module level pe hai hi nahi, wo enclosing function me hai. Bas ye rule pakad lo aur 80% confusion khatam.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)