Skip to content

    Scope & Closures

    Python · Intermediate

    Definition

    Python resolves names by LEGB (Local, Enclosing, Global, Built-in); closures remember enclosing variables.

    Explains decorators, callbacks and many bugs.

    Diagram

    LocalEnclosingGlobalBuilt-in

    Flowchart

    Look in localThen enclosingThen globalThen built-ins

    Example: Counter closure

    def counter():
        n = 0
        def inc():
            nonlocal n
            n += 1
            return n
        return inc
    c = counter()
    c(); c()
    print(c())

    Output: 3

    Key points

    • nonlocal edits enclosing variables
    • global edits module variables

    Interview questions

    What is a closure?

    A function that keeps access to variables from the scope it was created in.

    More Python topics