--- id: python-scope title: "Python Scope" category: "Programming_Language" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["LEGB rule", "nonlocal", "파이썬 스코프"] duplicate_of: "" source_trust_level: "B" confidence_score: 0.9 created_at: 2026-07-04 updated_at: 2026-07-04 review_reason: "" merge_history: [] tags: ["python", "programming", "w3schools", "scope", "global", "nonlocal", "legb"] raw_sources: ["https://www.w3schools.com/python/python_scope.asp"] applied_in: [] github_commit: "" --- # [[Python Scope]] ## 🎯 한 줄 통찰 (One-line insight) Python resolves a variable name by searching Local → Enclosing → Global → Built-in scopes in that order (the LEGB rule), and `global`/`nonlocal` are the two keywords that let inner code write to an outer scope instead of shadowing it. [S1] ## 🧠 핵심 개념 (Core concepts) - **Scope** — the region where a variable is accessible. [S1] - **Local scope** — a variable created inside a function is only usable inside that function (and functions nested within it). [S1] - **Global scope** — a variable created at the top level of a module is usable everywhere. [S1] - **Same-name shadowing** — a local variable with the same name as a global one is treated as a SEPARATE variable — the local one shadows the global inside the function, without affecting the global. [S1] - **`global` keyword** — lets a function create or modify a variable in the global scope. [S1] - **`nonlocal` keyword** — lets a nested function modify a variable belonging to its enclosing (outer) function, not the module-level global scope. [S1] - **LEGB rule** — name resolution order: Local → Enclosing → Global → Built-in. [S1] ## 🧩 추출된 패턴 (Extracted patterns) - **`global` vs `nonlocal` target different levels** — `global` reaches all the way to module scope; `nonlocal` reaches only the nearest enclosing FUNCTION scope, not the module — picking the wrong one is a common source of `SyntaxError` or silent shadowing. [S1] ## 📖 세부 내용 (Details) - Local scope: `def myfunc(): x = 300; print(x)` — x unavailable outside. [S1] - Global scope: `x = 300; def myfunc(): print(x); myfunc(); print(x)`. [S1] - Shadowing: `x = 300; def myfunc(): x = 200; print(x); myfunc(); print(x)` — prints 200 then 300. [S1] - `global` to modify: `def myfunc(): global x; x = 200; myfunc(); print(x)`. [S1] - `nonlocal` to modify enclosing scope: `def myfunc1(): x = "Jane"; def myfunc2(): nonlocal x; x = "hello"; myfunc2(); return x`. [S1] - LEGB demonstration: nested `outer()`/`inner()` each define `x`; each print shows the scope-appropriate value. [S1] ## ⚖️ 모순 및 업데이트 (Contradictions & updates) 소스에서 모순되는 정보는 발견되지 않음. ## 🛠️ 적용 사례 (Applied in summary) 현재 발견된 실제 적용 사례가 없습니다 — Decorators 챕터의 클로저(inner function이 outer function의 변수를 참조하는 패턴)가 이 Enclosing 스코프 개념에 직접 의존한다. [S1] ## 💻 코드 패턴 (Code patterns) nonlocal modifies the enclosing function's variable (Python): ```python def myfunc1(): x = "Jane" def myfunc2(): nonlocal x x = "hello" myfunc2() return x print(myfunc1()) # hello ``` ## ✅ 검증 상태 및 신뢰도 - **상태:** draft - **검증 단계:** conceptual - **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body) - **신뢰 점수:** 0.90 - **중복 검사 결과:** 신규 생성 (New discovery) ## 🔗 지식 그래프 (Knowledge Graph) - **상위/루트:** [[Python Tutorial]] - **관련 개념:** [[Python Global Variables]], [[Python Decorators]], [[Python Lambda]] - **참조 맥락:** 변수 이름 해석 규칙(LEGB)의 기초 — 데코레이터/클로저 이해에 필수. ## 📚 출처 (Sources) - [S1] W3Schools — Python Scope — https://www.w3schools.com/python/python_scope.asp ## 📝 변경 이력 (Change history) - 2026-07-04: Initial draft synthesized from the W3Schools "Python Scope" page (Astra wiki-curation, P-Reinforce v3.1 format).