[New-bugs-announce] [issue42597] Improve documentation of locals() w.r.t. "free variables" vs. global variables
Dominik V.
report at bugs.python.org
Tue Dec 8 05:19:27 EST 2020
New submission from Dominik V. <dominik.vilsmeier1123 at gmail.com>:
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 (https://docs.python.org/3/reference/executionmodel.html#binding-of-names):
> 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():
print(locals())
y = x
bar()
foo()
```
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: https://stackoverflow.com/questions/12919278/how-to-define-free-variable-in-python
By the way, would it be helpful to add the term "free variable" to the glossary (https://docs.python.org/3/glossary.html)?
----------
assignee: docs at python
components: Documentation
messages: 382721
nosy: Dominik V., docs at python
priority: normal
severity: normal
status: open
title: Improve documentation of locals() w.r.t. "free variables" vs. global variables
type: enhancement
versions: Python 3.10
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42597>
_______________________________________
More information about the New-bugs-announce
mailing list