Title: Improve documentation of locals() w.r.t. "free variables" vs. global variables
Type: enhancement Stage:
Components: Documentation Versions: Python 3.10
Status: open Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: Dominik V., docs@python
Priority: normal Keywords:

Created on 2020-12-08 10:19 by Dominik V., last changed 2020-12-08 10:19 by Dominik V..

Messages (1)
msg382721 - (view) Author: Dominik Vilsmeier (Dominik V.) * Date: 2020-12-08 10:19
The documentation of locals() mentions that:

> Free variables are returned by locals() when it is called in function blocks [...]

The term "free variable" is defined in the documentation about the execution model (

> If a variable is used in a code block but not defined there, it is a free variable.

That definition includes global variables (and builtin ones), but these are not returned by locals(). For example compare the following:

x = 1
def foo():
    # global x
    x = 1
    def bar():
        y = x

If the `global x` is commented then it prints {'x': 1}, and if it is uncommented it prints {}. The same holds for names of builtins.

So the documentation of locals() could mention this in the following way (emphasis added):

> Free variables *of enclosing functions* are returned by locals() when it is called in function blocks [...]


There is also a StackOverflow question, that describes this confusion:

By the way, would it be helpful to add the term "free variable" to the glossary (
Date User Action Args
2020-12-08 10:19:27Dominik V.create