Look at the following code snippet as an explanation:
a, b, c = 1, 2, 3
def fun1():
a = 4
def fun2():
b = 5
print a,b,c
fun2()
>>> fun1()
4 5 3
>>> print a,b,c
1 2 3
When you define a function, it 'inherits' variables from the calling scope.
Obviously, once you redefine that variable locally within a function, then the local definition applies for the remainder1 of the function.
This is why fun1
inherits b
and c
, defined at "top level" (i.e. fun1
's enclosing scope), which it then passes on further to the 'nested' function fun2
.
fun2
(whose enclosing scope is fun1
) then inherits a
as defined within fun1
, as well as b
and c
, since this was inherited by fun1
.
Specifically, note that a
inside fun2
is 4
, not the global 1
(as another answer here seemed to suggest).
When you only have one function defined at top level, you could conceptually perceive that as being 'nested' at the top level, and therefore inherits the variables defined at top level (i.e. effectively global scope, even if not explicitly defined as such via the global keyword).
Have a look at help("NAMESPACES")
for more details
1.To be clear, I don't mean that you can use the inherited value for a while and suddenly define a local version half-way through; if you do this python will complain that you tried to "use a local variable before assignment". I just mean that you either use the inherited version, or explicitly redefine it, which effectively makes it a local variable of the same name for use in that function.