The local/global/free variable definitions from python doc:
If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable.
Code 1:
>>> x = 0
>>> def foo():
... print(x)
... print(locals())
...
>>> foo()
0
{}
Code 2:
>>> def bar():
... x = 1
... def foo():
... print(x)
... print(locals())
... foo()
...
>>> bar()
1
{'x':1}
Free variables are returned by locals()
when it is called in function blocks, but not in class blocks.
In Code 1
, x
is a global variable, and it's used but not defined in foo()
.
However it's not a free variable, because it's not returned by locals()
.
I think it's not what the doc said. Is there a technical definition for free variable?