Worked examples — global and nonlocal keywords
1.2.31 · D3· Coding › Introduction to Programming (Python) › global and nonlocal keywords
Yeh note global and nonlocal keywords ka worked-examples companion hai. Parent note ne aapko do rules sikhaye the:
- Ek function ke andar kisi bhi jagah kisi naam ko assign karna usse local bana deta hai poore function body ke liye (yeh compile time pe decide hota hai).
globalmodule top level tak pahunchta hai;nonlocalnearest enclosing function tak pahunchta hai.
Yahan hum sirf har possible case ko run karte hain taaki koi bhi scenario aapko surprise na kare. Agar neeche koi word unfamiliar lage (scope, closure, rebind), toh parent note aur Scope and LEGB rule usse define karte hain — hum sirf unhi ko assume karte hain.
Scenario matrix
Is topic se jo bhi situation aa sakti hai woh is table ke ek cell mein hai. Neeche ke examples mein har ek tagged hai apne cell(s) ke saath, aur milke yeh sab poora fill karte hain.
| # | Case class | Kya keyword chahiye? | Kaunsa? |
|---|---|---|---|
| C1 | Sirf outer variable padho (read-only) | Nahi | — |
| C2 | Ek module variable ko rebind karo | Haan | global |
| C3 | Ek enclosing-function variable ko rebind karo | Haan | nonlocal |
| C4 | Ek object (list/dict) ko mutate karo — naam pe = nahi |
Nahi | — |
| C5 | Degenerate: pehle rebind, phir read, no keyword | Crash hoga | UnboundLocalError |
| C6 | Wrong keyword: nonlocal ki jagah global |
Crash / miss | SyntaxError ya galat var |
| C7 | Zero enclosing scopes: module top / ek level pe nonlocal |
Crash hoga | SyntaxError |
| C8 | Deep nesting — nonlocal sirf nearest enclosing pick karta hai |
Haan | nonlocal (nearest) |
| C9 | Real-world word problem (shared counter / config) | Haan | global |
| C10 | Exam twist: global ek module var create karta hai jo pehle tha hi nahi |
Haan | global |

Example 1 — Sirf outer variable padho (C1)
Example 2 — Classic crash (C5)
Example 3 — Module variable ko rebind karo (C2)
Example 4 — Mutate karo, rebind mat karo (C4)
Example 5 — Closure with nonlocal (C3)
def make_counter():
n = 0
def step():
nonlocal n
n += 1
return n
return step
c = make_counter()
print(c(), c(), c())Forecast: 1 2 3, ya har call 1 se reset hoti hai?
Step 1 — n kahan rehta hai?
Yeh step kyun? n = 0 make_counter mein hai, jo step ka enclosing function hai — module nahi. Toh target scope E hai, G nahi.
Step 2 — step n ko rebind karta hai (n += 1 matlab n = n + 1).
Yeh step kyun? Naam par += ek rebind hai. nonlocal ke bina, step ek fresh local n banata aur use read karte waqt crash karta (closure ke andar C5). nonlocal n rebind ko enclosing n ki taraf point karta hai.
Step 3 — Closure n ko zinda rakhta hai.
Yeh step kyun? make_counter return karne ke baad bhi, step (ek closure) n ka reference rakhta hai, toh yeh calls ke beech survive karta hai: 0→1→2→3.
Verify: 1 2 3 print hota hai.
Example 6 — Wrong keyword: enclosing var ke liye global (C6)
def make_counter():
n = 0
def step():
global n # wrong!
n += 1
return n
return step
c = make_counter()
print(c())Forecast: Example 5 jaisa 1, ya kuch toot jaata hai?
Step 1 — global n MODULE ko dekhta hai, enclosing function ko nahi.
Yeh step kyun? global hamesha ground floor tak pahunchta hai. Enclosing n = 0 usse invisible hai.
Step 2 — n += 1 ek module n read karta hai jo exist hi nahi karta.
Yeh step kyun? Koi module-level n nahi hai, toh n + 1 NameError: name 'n' is not defined raise karta hai.
Verify: NameError raise hota hai. Rule: enclosing-function var ⇒ nonlocal, kabhi global nahi.
Example 7 — nonlocal bina kisi enclosing scope ke (C7)
def solo():
nonlocal y # no enclosing function above solo
y = 5Forecast: Runtime crash, ya Python run karne se pehle hi reject kar deta hai?
Step 1 — nonlocal ko ek enclosing function mein existing binding chahiye.
Yeh step kyun? solo module top level par hai; koi enclosing function nahi hai jo y hold kare. nonlocal ka koi target nahi hai.
Step 2 — Yeh compile time par pakda jaata hai.
Yeh step kyun? UnboundLocalError (runtime error) ke unlike, ek galat nonlocal ek SyntaxError: no binding for nonlocal 'y' found hai — Python start bhi nahi hoga.
Verify: Definition time par SyntaxError raise hota hai.
Example 8 — Deep nesting: nonlocal sirf nearest enclosing pick karta hai (C8)
def a():
x = "a"
def b():
x = "b"
def c():
nonlocal x
x = "c"
c()
return x
return b(), x
print(a())Forecast: Kya c b ka x badalta hai, a ka x, ya dono?
Step 1 — nonlocal NEAREST enclosing scope se bind karta hai jiske paas x ho.
Yeh step kyun? c se baahir ki taraf chalte hain: b ke paas x = "b" hai — yahi nearest hai. c usi ko rebind karta hai, kabhi a ke x ko nahi.
Step 2 — Values trace karo.
Yeh step kyun? c() b ke x ko "c" set karta hai. Toh b "c" return karta hai. a ka apna x "a" rehta hai, untouched.
Verify: ('c', 'a') print hota hai.

Example 9 — Real-world: shared config toggle (C9)
Ek logging module mein ek switch hai. Use kahin se bhi on karna poore program ko affect karna chahiye.
DEBUG = False
def enable_debug():
global DEBUG
DEBUG = True
def log(msg):
if DEBUG:
print("LOG:", msg)
log("first")
enable_debug()
log("second")Forecast: Kitni lines print hongi?
Step 1 — log sirf DEBUG read karta hai (C1): koi keyword nahi.
Yeh step kyun? log mein koi = DEBUG ko target nahi karta; reading module value tak chadh jaati hai.
Step 2 — enable_debug DEBUG ko rebind karta hai (C2): global chahiye.
Yeh step kyun? DEBUG = True module switch ki rebinding hai. global DEBUG usse shared variable par hit karta hai, ek throwaway local par nahi.
Step 3 — Trace karo.
Yeh step kyun? log("first") → DEBUG False hai → kuch nahi. enable_debug() → module DEBUG = True. log("second") → LOG: second print karta hai.
Verify: Exactly ek line print hoti hai: LOG: second. (Yeh ek deliberate global side effect hai — pure function nahi.)
Example 10 — Exam twist: global ek naya module variable create karta hai (C10)
def init():
global created
created = 99
init()
print(created)Forecast: created init run hone se pehle kabhi module level par define nahi hua tha — NameError?
Step 1 — global created ek module variable naam leta hai jo abhi exist nahi karta.
Yeh step kyun? global ko variable ka pehle se exist karna zaroori nahi. Yeh sirf kehta hai "naam created module scope ko refer karta hai."
Step 2 — Assignment use wahan create karta hai.
Yeh step kyun? created = 99 ek naya module-level naam bind karta hai. init() run hone ke baad, module scope mein ab created = 99 hai.
Verify: 99 print hota hai. Note: yeh sirf init() call hone ke baad exist karta hai — init() se pehle print(created) call karna NameError raise karega.
Recall Yeh kaunsa cell hai? Quick self-test
total = 0
def add(v):
total += v
add(5)Answer ::: Cell C5 — total += v total ko rebind karta hai, use local banata hai; RHS assignment se pehle use read karta hai → UnboundLocalError. global total se fix karo.
Naam par = (ya +=) dikh raha hai? → aap rebinding kar rahe ho → global (module) ya nonlocal (enclosing) chuno. Sirf .append() call / reading? → koi keyword nahi chahiye.
Connections
- global and nonlocal keywords
- Scope and LEGB rule
- Functions in Python
- Closures
- Mutable vs Immutable objects
- UnboundLocalError
- Pure functions and side effects