Skip to content

Clarify which variables appear in function.__closure__ #142093

@Vemulakonda559

Description

@Vemulakonda559

While working with nested functions, I observed that function.__closure__ only
contains cells for variables that are actually referenced inside the inner
function body. Variables defined in the enclosing scope but not used in the
inner function do not appear in co_freevars and therefore do not appear in
function.__closure__.

Example:

def outer():
    x = 1
    y = 2
    z = 3
    def inner():
        return x
    return inner

inner.__closure__  # contains only x

This behavior matches the execution model (“free variables”), but the current
documentation only states that __closure__ contains bindings for names listed
in co_freevars. It does not explicitly state that only referenced names are
included.

This PR proposes adding a brief clarification to make this behavior explicit.

Before continuing with the pull request, I would like confirmation from the
documentation team whether this detail should be included in the data model
section.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions