[docs] [issue26683] Questionable terminology for describing what locals() does

Marco Buttu report at bugs.python.org
Sat Dec 3 08:56:18 EST 2016

Marco Buttu added the comment:

The documentation [1] says: "If a variable is used in a code block but not defined there, it is a free variable." According to this description,  it seems to me that the variable ``x`` is free in ``foo()``::

  >>> def foo():
  ...     print(x)

But actually for the code object it is not::

  >>> foo.__code__.co_freevars

The meaning of free variable used for the code object is consistent with the ``locals()`` documentation [2]: "Free variables are returned by locals() when it is called in function blocks". In fact, in the following code ``x` is not a free variable for ``locals()``::

  >>> def foo():
  ...     print(x)
  ...     print(locals())
  >>> x = 3
  >>> foo()

So, I thing there is an inconsistency between the definition of "free variable" given in [1] and the meaning of "free variable" both in the code object and in the ``locals()`` documentation [2]. 
But if we change the definition of "free variable" according to the meaning of both the code object and ``locals()``, I am afraid we go in the wrong direction, because I suspect for most people the proper definition of free variable is the one given in [1]. Also for Wikipedia [3]: "In computer programming, the term free variable refers to variables used in a function that are neither local variables nor parameters of that function.".

Instead, if we keep or remove the definition of "free variable" given in [1], I agree with Terry to change the ``locals()`` documentation, writing that "``locals()`` includes also the locals of the surrounding function contexts, even though they are called 'nonlocal' within the nested function.". Maybe it is also worth adding a shell example, to better clarify. 

So, at the end, to me the ideal solution would be to keep in [1] the current definition of "free variable", to change the ``locals()`` documentation according to Terry suggestion, and to change the behavior of ``code.co_freevars`` (maybe not only this) in order to fit the definition.

[1] https://docs.python.org/3/reference/executionmodel.html#naming-and-binding
[2] https://docs.python.org/3/library/functions.html#locals
[3] https://en.wikipedia.org/wiki/Free_variables_and_bound_variables

nosy: +marco.buttu

Python tracker <report at bugs.python.org>

More information about the docs mailing list