Following from this excellent answer, there are only four scopes in Python.
LEGB Rule.
L. Local. (Names assigned in any way within a function (def or
lambda)), and not declared global in that function.
E. Enclosing function locals. (Name in the local scope of any and all
enclosing functions (def or lambda), form inner to outer.
G. Global (module). Names assigned at the top-level of a module file,
or declared global in a def within the file.
B. Built-in (Python). Names preassigned in the built-in names module :
open,range,SyntaxError,...
As you can see, based on indentation/control block, python doesn't limit the visibility of the variables.
So, if that code is within a function, then the variable will be visible to all parts of the code within that function, after its creation.
If that code is within a module, then the variable will be visible to all parts of the module, after its creation.
When you try to access a variable, first the local scope will be searched, if not found then the closure scope will be searched, if not found then module scope will be searched, if not found builtin scope will be searched, and if not found error will be thrown.
Check this function now,
def func(x):
if x == 0: y = 1
print locals()
func(1)
func(0)
Output
{'x': 1}
{'y': 1, 'x': 0}
In the first case, y
is not created and so it is not there in local scope. But in the second case, y
is added to the local scope, so, it will be visible to all the code which share the local scope.