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.
    • nonlocal and global declare write-through.

    Syntax reference

    Visual flow / code:

    python
    def make_counter():
    count = 0
    def increment():
    nonlocal count
    count += 1
    return count
    return increment
    c = make_counter()
    print(c()) # 1
    print(c()) # 2
    print(c()) # 3

    Execution workflow

    1Scope & Closures (LEGB) Workflow
    1 / 4

    Step 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 nonlocal for closures.
    • Keep state in classes when complex.

    Common mistakes

    • Forgetting nonlocal creates a new local var, not the outer one.

    Hands-on exercise

    Interview preparation — practice these questions:

    • What's LEGB?
    • What's a closure?
    • nonlocal vs global?

    Summary

    In summary: LEGB rules name lookup. Closures = functions + captured scope.

    Ready to mark this lesson complete?Track your journey across the entire course.