[Tutor] Question about why a list variable is apparently global.

Dave Angel davea at davea.name
Thu Nov 27 17:23:17 CET 2014


On 11/27/2014 11:07 AM, boB Stepp wrote:

x = "outer"

>
>>>> def tricky_func2():
>                y = x
>                print(x)
>
>>>> tricky_func2()
> outer
>
> So why does not print(x) see the global x and instead looks for the
> local x?

The function is compiled during the import (or initial load if it's a 
script);  it cannot be called until the compile is complete.  During 
that compile, a list of local variables is built for that function, 
based on DEFINITIONS of variables, not on REFERENCES to variables.  At 
compile time, no knowledge of global variables is possible.

How are local variable definitions to be recognized?
   1) any 'global' or 'nonlocal' statement declares that the variable is 
NOT local, even if the following might otherwise make it so.
   2) formal parameters
   3) assignment statements such as y =  zzzzz  or  x,y = zzzz
   4) with statements having an "as" clause
   5) except statements having an 'as" clause

I may have missed one, but everything else is NOT a local variable.  The 
list of locals is unchangeable at runtime.  So any other references to 
variables must be searched for at run time.  The search mechanism is a 
bit more complex than I want to go into here, but includes globals, 
built-ins, and a few other things.


>  And why is this different between classes and functions?
>

Classes are not compiled in the same sense.  The stuff inside a class, 
but not inside a method is evaluated at the same time as top-level 
stuff.  So the rules are a bit different than either top-level or 
function/method.


-- 
DaveA


More information about the Tutor mailing list