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?
Definition of a free variable: Used, but neither global nor bound.
For example:
xis not free in Code 1, because it’s a global variable.xis not free inbar()in Code 2, because it’s a bound variable.xis free infoo().Python makes this distinction because of closures. A free variable is not defined in the current environment, i. e. collection of local variables, and is also not a global variable! Therefore it must be defined elsewhere. And this is the concept of closures. In Code 2,
foo()closes onxdefined inbar(). Python uses lexical scope. This means, the interpreter is able to determine the scope by just looking at the code.For example:
xis known as a variable infoo(), becausefoo()is enclosed bybar(), andxis bound inbar().Global scope is treated specially by Python. It would be possible to view the global scope as an outermost scope, but this is not done because of performance (I think). Therefore it is not possible that
xis both free and global.Exemption
Life is not so simple. There exist free global variables. Python docs (Execution model) says:
I didn’t know that myself. We are all here to learn.