Skip to content

Commit 2739099

Browse files
ncoghlanwillingc
andauthored
gh-70870: Clarify dual usage of 'free variable' (#122545)
The term "free variable" has unfortunately become genuinely ambiguous over the years (presumably due to the names of some relevant code object instance attributes). While we can't eliminate that ambiguity at this late date, we can at least alert people to the potential ambiguity by describing both the formal meaning of the term and the common alternative use as a direct synonym for "closure variable". --------- Co-authored-by: Carol Willing <[email protected]>
1 parent cc9b9be commit 2739099

File tree

9 files changed

+66
-21
lines changed

9 files changed

+66
-21
lines changed

Doc/c-api/code.rst

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,13 @@ bound into a function.
3232
3333
.. c:function:: Py_ssize_t PyCode_GetNumFree(PyCodeObject *co)
3434
35-
Return the number of free variables in a code object.
35+
Return the number of :term:`free (closure) variables <closure variable>`
36+
in a code object.
3637
3738
.. c:function:: int PyUnstable_Code_GetFirstFree(PyCodeObject *co)
3839
39-
Return the position of the first free variable in a code object.
40+
Return the position of the first :term:`free (closure) variable <closure variable>`
41+
in a code object.
4042
4143
.. versionchanged:: 3.13
4244
@@ -144,7 +146,8 @@ bound into a function.
144146
145147
Equivalent to the Python code ``getattr(co, 'co_freevars')``.
146148
Returns a new reference to a :c:type:`PyTupleObject` containing the names of
147-
the free variables. On error, ``NULL`` is returned and an exception is raised.
149+
the :term:`free (closure) variables <closure variable>`. On error, ``NULL`` is returned
150+
and an exception is raised.
148151
149152
.. versionadded:: 3.11
150153

Doc/glossary.rst

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,28 @@ Glossary
231231
A variable defined in a class and intended to be modified only at
232232
class level (i.e., not in an instance of the class).
233233

234+
closure variable
235+
A :term:`free variable` referenced from a :term:`nested scope` that is defined in an outer
236+
scope rather than being resolved at runtime from the globals or builtin namespaces.
237+
May be explicitly defined with the :keyword:`nonlocal` keyword to allow write access,
238+
or implicitly defined if the variable is only being read.
239+
240+
For example, in the ``inner`` function in the following code, both ``x`` and ``print`` are
241+
:term:`free variables <free variable>`, but only ``x`` is a *closure variable*::
242+
243+
def outer():
244+
x = 0
245+
def inner():
246+
nonlocal x
247+
x += 1
248+
print(x)
249+
return inner
250+
251+
Due to the :attr:`codeobject.co_freevars` attribute (which, despite its name, only
252+
includes the names of closure variables rather than listing all referenced free
253+
variables), the more general :term:`free variable` term is sometimes used even
254+
when the intended meaning is to refer specifically to closure variables.
255+
234256
complex number
235257
An extension of the familiar real number system in which all numbers are
236258
expressed as a sum of a real part and an imaginary part. Imaginary
@@ -454,6 +476,13 @@ Glossary
454476
the :term:`global interpreter lock` which allows only one thread to
455477
execute Python bytecode at a time. See :pep:`703`.
456478

479+
free variable
480+
Formally, as defined in the :ref:`language execution model <bind_names>`, a free
481+
variable is any variable used in a namespace which is not a local variable in that
482+
namespace. See :term:`closure variable` for an example.
483+
Pragmatically, due to the name of the :attr:`codeobject.co_freevars` attribute,
484+
the term is also sometimes used as a synonym for :term:`closure variable`.
485+
457486
function
458487
A series of statements which returns some value to a caller. It can also
459488
be passed zero or more :term:`arguments <argument>` which may be used in

Doc/library/dis.rst

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1434,7 +1434,7 @@ iterations of the loop.
14341434
slot ``i`` of the "fast locals" storage in this mapping.
14351435
If the name is not found there, loads it from the cell contained in
14361436
slot ``i``, similar to :opcode:`LOAD_DEREF`. This is used for loading
1437-
free variables in class bodies (which previously used
1437+
:term:`closure variables <closure variable>` in class bodies (which previously used
14381438
:opcode:`!LOAD_CLASSDEREF`) and in
14391439
:ref:`annotation scopes <annotation-scopes>` within class bodies.
14401440

@@ -1463,8 +1463,8 @@ iterations of the loop.
14631463

14641464
.. opcode:: COPY_FREE_VARS (n)
14651465

1466-
Copies the ``n`` free variables from the closure into the frame.
1467-
Removes the need for special code on the caller's side when calling
1466+
Copies the ``n`` :term:`free (closure) variables <closure variable>` from the closure
1467+
into the frame. Removes the need for special code on the caller's side when calling
14681468
closures.
14691469

14701470
.. versionadded:: 3.11
@@ -1937,10 +1937,10 @@ instructions:
19371937

19381938
.. data:: hasfree
19391939

1940-
Sequence of bytecodes that access a free variable. 'free' in this
1941-
context refers to names in the current scope that are referenced by inner
1942-
scopes or names in outer scopes that are referenced from this scope. It does
1943-
*not* include references to global or builtin scopes.
1940+
Sequence of bytecodes that access a :term:`free (closure) variable <closure variable>`.
1941+
'free' in this context refers to names in the current scope that are
1942+
referenced by inner scopes or names in outer scopes that are referenced
1943+
from this scope. It does *not* include references to global or builtin scopes.
19441944

19451945

19461946
.. data:: hasname

Doc/library/functions.rst

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -684,9 +684,10 @@ are always available. They are listed here in alphabetical order.
684684
``__builtins__`` dictionary into *globals* before passing it to :func:`exec`.
685685

686686
The *closure* argument specifies a closure--a tuple of cellvars.
687-
It's only valid when the *object* is a code object containing free variables.
688-
The length of the tuple must exactly match the number of free variables
689-
referenced by the code object.
687+
It's only valid when the *object* is a code object containing
688+
:term:`free (closure) variables <closure variable>`.
689+
The length of the tuple must exactly match the length of the code object'S
690+
:attr:`~codeobject.co_freevars` attribute.
690691

691692
.. audit-event:: exec code_object exec
692693

Doc/library/symtable.rst

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,11 +167,12 @@ Examining Symbol Tables
167167

168168
.. method:: get_nonlocals()
169169

170-
Return a tuple containing names of nonlocals in this function.
170+
Return a tuple containing names of explicitly declared nonlocals in this function.
171171

172172
.. method:: get_frees()
173173

174-
Return a tuple containing names of free variables in this function.
174+
Return a tuple containing names of :term:`free (closure) variables <closure variable>`
175+
in this function.
175176

176177

177178
.. class:: Class

Doc/library/types.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ Standard names are defined for the following types:
199199
.. data:: CellType
200200

201201
The type for cell objects: such objects are used as containers for
202-
a function's free variables.
202+
a function's :term:`closure variables <closure variable>`.
203203

204204
.. versionadded:: 3.8
205205

Doc/reference/datamodel.rst

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -564,8 +564,9 @@ Special read-only attributes
564564
in which the function was defined.
565565

566566
* - .. attribute:: function.__closure__
567-
- ``None`` or a :class:`tuple` of cells that contain bindings for the
568-
function's free variables.
567+
- ``None`` or a :class:`tuple` of cells that contain bindings for the names specified
568+
in the :attr:`~codeobject.co_freevars` attribute of the function's
569+
:attr:`code object <function.__code__>`.
569570

570571
A cell object has the attribute ``cell_contents``.
571572
This can be used to get the value of the cell, as well as set the value.
@@ -1285,10 +1286,14 @@ Special read-only attributes
12851286

12861287
* - .. attribute:: codeobject.co_cellvars
12871288
- A :class:`tuple` containing the names of :ref:`local variables <naming>`
1288-
that are referenced by nested functions inside the function
1289+
that are referenced from at least one :term:`nested scope` inside the function
12891290

12901291
* - .. attribute:: codeobject.co_freevars
1291-
- A :class:`tuple` containing the names of free variables in the function
1292+
- A :class:`tuple` containing the names of
1293+
:term:`free (closure) variables <closure variable>` that a :term:`nested scope`
1294+
references in an outer scope. See also :attr:`function.__closure__`.
1295+
1296+
Note: references to global and builtin names are *not* included.
12921297

12931298
* - .. attribute:: codeobject.co_code
12941299
- A string representing the sequence of :term:`bytecode` instructions in

Doc/reference/executionmodel.rst

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ If a name is bound in a block, it is a local variable of that block, unless
9090
declared as :keyword:`nonlocal` or :keyword:`global`. If a name is bound at
9191
the module level, it is a global variable. (The variables of the module code
9292
block are local and global.) If a variable is used in a code block but not
93-
defined there, it is a :dfn:`free variable`.
93+
defined there, it is a :term:`free variable`.
9494

9595
Each occurrence of a name in the program text refers to the :dfn:`binding` of
9696
that name established by the following name resolution rules.
@@ -337,6 +337,9 @@ enclosing namespace, but in the global namespace. [#]_ The :func:`exec` and
337337
:func:`eval` functions have optional arguments to override the global and local
338338
namespace. If only one namespace is specified, it is used for both.
339339

340+
.. XXX(ncoghlan) above is only accurate for string execution. When executing code objects,
341+
closure cells may now be passed explicitly to resolve co_freevars references.
342+
Docs issue: https://github.com/python/cpython/issues/122826
340343
341344
.. _exceptions:
342345

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Clarified the dual usage of the term "free variable" (both the formal
2+
meaning of any reference to names defined outside the local scope, and the
3+
narrower pragmatic meaning of nonlocal variables named in ``co_freevars``).

0 commit comments

Comments
 (0)