python / python/cpython

Tutorial on defining functions has potentially misleading explanation of closure

Aperta
#150,837 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

docs
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Apri la sezione del tutorial all’indirizzo docs.python.org/3/tutorial/controlflow.html#defining-functions e rivedi la formulazione relativa alle tabelle dei simboli locali delle funzioni che racchiudono la definizione. Controlla il PR collegato gh-151038 prima di apportare modifiche; il lavoro è completato quando la spiegazione si riferisce chiaramente alle funzioni che racchiudono la definizione, non alla chiamata.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
1/5
Tempo stimato
Meno di un'ora
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
30/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.