1.2.30 · D1 · HinglishIntroduction to Programming (Python)

FoundationsVariable scope — LEGB rule (Local, Enclosing, Global, Built-in)

3,039 words14 min read↑ Read in English

1.2.30 · D1 · Coding › Introduction to Programming (Python) › Variable scope — LEGB rule (Local, Enclosing, Global, Built-

Is page ka ek hi kaam hai: parent note jo bhi vocabulary use karta hai usse puri tarah se sikhana, "name kya hota hai?" se shuru karke — taaki jab tum char-letter rule se milo (jo hum end mein puri tarah spell out karenge), tab tak har letter ka matlab koi aisi cheez ho jo tum dekh sako. Yahaan yeh assume nahi kiya gaya ki tumne pehle kabhi code kiya hai.


1. Ek name ek label hai, box nahi

Figure dekho. Yellow value 5 memory mein kahin baithi hai. Blue label x ek arrow hai jo uski taraf point kar raha hai. Yahi poora game hai:

  • x = 5 — label x ko value 5 se attach karo.
  • x = 9x ko 5 se uthao, 9 pe re-stick karo. 5 untouched rehta hai; sirf arrow move hua.

2. Ek namespace labels ki ek page hai

Figure mein, ek namespace ko ek do-column page ki tarah draw kiya gaya hai. Parent note kehta hai namespaces "backed by a dictionary" hote hain — ek dictionary exactly yahi hai: keys (names) aur values ki ek table. Ise formally Namespaces and the dict model mein seekhoge; yahaan tumhe bas labels ki page ki picture chahiye.

Topic ko yeh kyun chahiye: lookup rule woh order hai jisme Python tumhara name dhoondne ke liye kai aisi pages flip karta hai. Pages nahi, toh search karna kya?


3. Ek function spot pe bani ek fresh page hai

Figure do stacked pages dikhata hai: module page (hamesha open, bottom pe) aur ek function page (call ke through open hoti hai, upar baithi hoti hai). Yeh stack — pages jo calls hone pe pile up hoti jaati hain — woh physical cheez hai jisme lookup rule walk karta hai. Iske baare mein aur depth mein Functions and Parameters mein jaoge.


4. Nesting — ek page jo doosri page ke khule rehne par khulti hai

Yeh "abhi bhi open page neeche" woh cheez hai jis par Closures and Nested Functions bana hai. Nesting ke bina, search karne ke liye koi "enclosing" page hoti hi nahi.


5. Built-ins — woh page jo tumne kabhi nahi likhi


6. Name ko read karna vs. likhna — do verbs

Yeh distinction poore topic ka hinge hai. Reading pages ke through search trigger karta hai. Writing kuch surprising karta hai: by default label ko current function ki page pe rakhta hai, bina kisi search ke. Kyunki ek akela x = ... x ko poore function ke liye current page se belonging mark kar deta hai, usi function mein pehle ki ek read fail ho sakti hai — famous UnboundLocalError. Yeh split crisp rakho; baaki sab kuch isi pe depend karta hai.

"Advance mein decide" kyun hota hai — compile-time WHY

Figure dekho. Left panel mein Python scan karta hai aur count = ... dhoondh leta hai, toh count ko function ki page se belonging ka pre-stamp lag jaata hai — koi bhi line run hone se pehle. Right panel mein, execution pehli line pe count + 1 tak pahunchti hai, count ko function ki page se read karne ki koshish karti hai, aur label abhi tak kisi cheez se chipka nahiUnboundLocalError. Isliye decision surprising lagta hai: yeh pre-scan ke dauran liya gaya tha, na ki jab offending line chali.


7. Opt out karna — global aur nonlocal

Default "ek write current page pe jaati hai" sirf ek default hai. Do keywords tumhe redirect karne dete hain ki write ka label kahan chipke.


8. Edge cases: har block apna page nahi banata

Ek smart trap yeh manna hai ki koi bhi indented block apna page banata hai. Aisa nahi hota. Sirf teen cheezein ek naya namespace page banati hain.


9. Rule ka naam: L → E → G → B

Ab har letter ka matlab kuch aisa hai jo tum picture kar sako, toh acronym batana safe hai.

Woh ek sequence — plus write rule (§6) aur do opt-out keywords (§7) — yahi poora parent topic hai. Wahan har worked example bas Python ka in chaar arrows pe chalna hai.


Prerequisite map

Is map ko bottom-up padho: har box upar ka ek section hai, aur arrows ka matlab hai "yeh pehle chahiye usse pehle." Left side ke teen sources (name, read-vs-write) aur beech mein page-machinery sab final rule ko feed karte hain.

A name is a label on a value

A namespace is a page of labels

A function call opens a new page

Nesting keeps the outer page open

Built-in page is always open at the bottom

Comprehensions and class bodies are special pages

Reading versus writing a name

global and nonlocal redirect a write

Search order Local Enclosing Global Built-in

The full LEGB scope rule

  • name → namespace: labels ki page tab tak nahi ho sakti jab tak yeh na pata ho ki label sirf ek pointer hai.
  • namespace → function call: pages tab banti hain jab calls unhe create karti hain.
  • read-vs-write → global/nonlocal: keywords tab hi samajh aate hain jab yeh dikh jaaye ki likhne ka ek default target hota hai jise shayad tum override karna chaho.
  • everything → the full rule: acronym tabhi trustworthy hai jab har letter, plus write rule aur edge-case pages, samajh aa jaaye.

Equipment checklist

Right side dhako aur khud ko test karo. Agar koi answer fuzzy lage, parent note tackle karne se pehle woh section dobara padho.

Python mein ek name ko best picture kiya jaata hai
ek sticky label (ek arrow) ki tarah jo memory mein kisi value ki taraf point karta hai, na ki use hold karne wala box.
Ek namespace hota hai
ek page/table jo names ko values se map karta hai, yaani {name → value}.
Kaunsi event ek naya namespace page banati hai
ek function call karna — har call ek fresh, private page kholti hai.
Lookup rule jinhe search karta hai woh chaar page-types hain
Local (current function), Enclosing (outer function), Global (module), Built-in (Python ki pre-loaded page).
len jaisi built-in names kahan rehti hain
built-in page pe, jise Python bottom pe hamesha open rakhta hai aur last mein check karta hai.
Name ko read aur write karne mein farq
reading ek label dhoondti/use karti hai (L→E→G→B search trigger hoti hai); writing (x = ...) ek label rakhti hai, default se current function ki page pe bina kisi search ke.
Write ka target "advance mein decide" kyun hota hai
Python poori function body ko run karne se pehle pre-scan karta hai aur har likhe hue naam ko us page se belonging ka stamp deta hai — toh write ke upar ki read bhi usi page ko use karti hai.
global x kya karta hai
x ki writes ko module (Global) page pe redirect karta hai, naya local label banane ki jagah.
nonlocal x kya karta hai
x ki writes ko nearest enclosing function ki page pe redirect karta hai; naam wahan pehle se exist karna chahiye.
Kya for/if blocks ek naya page banate hain
nahi — sirf functions, module, class bodies, aur comprehensions banate hain; for/if mein names enclosing page ke hote hain.
Kya comprehension ka loop variable bahar nikalti hai
nahi — Python 3 mein comprehension ki apni private page hoti hai, toh loop variable baad mein gone ho jaata hai (plain for loop se alag, jo leak karta hai).
Kya ek method class-body name ko "enclosing" ki tarah dekh sakta hai
nahi — enclosing search class bodies ko skip karta hai; method ko class-body names self. ya ClassName. se reach karne chahiye.
Exact search order
Local → Enclosing → Global → Built-in, pehle match pe rukna, warna NameError.

Connections

  • Yeh note Hinglish mein →
  • Functions and Parameters — ek call hi woh cheez hai jo naya Local page kholti hai.
  • Closures and Nested Functions — Enclosing (E) page ke khule rehne pe bana hai.
  • Namespaces and the dict model — "labels ki page" precisely batayi gayi hai.
  • NameError and UnboundLocalError — search aur write rule ke failure modes.
  • Modules and import — Global page kaise fill hoti hai.