Python Tutorial 0/52 lessons ~6 min read Lesson 13
Scope & Closures (LEGB)
Python resolves names using LEGB: Local → Enclosing → Global → Built-in.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
Python resolves names using LEGB: Local → Enclosing → Global → Built-in. Closures capture enclosing-scope variables — essential for decorators.
Understanding the topic
Core concepts to understand:
- Local: inside the function.
- Enclosing: outer function (closure).
- Global: module level.
- Built-in:
print,len, etc. nonlocalandglobaldeclare write-through.
Syntax reference
Visual flow / code:
python
def make_counter():count = 0def increment():nonlocal countcount += 1return countreturn incrementc = make_counter()print(c()) # 1print(c()) # 2print(c()) # 3
Execution workflow
1Scope & Closures (LEGB) Workflow
1 / 4Step 1
Local: inside the function.
Apply this step while implementing scope & closures (legb) in real code.
Real-world use
Closures power decorators, factory functions, and stateful callbacks. Understand LEGB before tackling decorators.
Best practices
- Avoid
global— return values instead. - Use
nonlocalfor closures. - Keep state in classes when complex.
Common mistakes
- Forgetting
nonlocalcreates a new local var, not the outer one.
Hands-on exercise
Interview preparation — practice these questions:
- What's LEGB?
- What's a closure?
nonlocalvsglobal?
Summary
In summary: LEGB rules name lookup. Closures = functions + captured scope.
Ready to mark this lesson complete?Track your journey across the entire course.