python / python/cpython

Clarify which variables appear in function.__closure__

Open
#142,093 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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
  • gh-142086

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in the Python data model documentation and review the existing description of function.closure alongside co_freevars. Clarify that only names referenced by the inner function appear, and confirm the wording with the documentation team before proceeding; done means the behavior is explicit in the relevant section.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.