python / python/cpython

Tutorial on defining functions has potentially misleading explanation of closure

Open
#150,837 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

Documentation

Apologies if I'm using the term closure wrong, I come from more of a Scheme background.

The tutorial says that variable references look "in the local symbol tables of enclosing functions". However, it is not obvious that this refers to functions enclosing the definition, rather than functions enclosing a call to the function. When I first read it I was somewhat confused as it seemed to contradict what I knew about closure in Python.

The following demonstrates half of this:

>>> def f():
...     print(n)
...     
>>> n = 1
>>> f()
1
>>> def g():
...     n = 2
...     f()
...     
>>> g()
1
>>>

If the variable reference looked in the executing function's local symbol table, we would expect that the last call to g would print 2, rather than 1. However, it does not look in the symbol table of the function enclosing its call, going straight to the global symbol table.

This demonstrates the other half, where the value is obtained from the local symbol table of the function enclosing the call:

>>> def f():
...     def g():
...         print(n)
...     n = 1
...     g()
...     n = 2
...     g()
...     
>>> f()
1
2
>>> 

In my opinion all that is required is a change in wording, perhaps to "functions enclosing the definition".

Linked PRs
  • gh-151038

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

Open the tutorial section at docs.python.org/3/tutorial/controlflow.html#defining-functions and review the wording about local symbol tables of enclosing functions. Check the linked PR gh-151038 before making any changes; done means the explanation clearly refers to functions enclosing the definition rather than the call.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.