Python resolves your variables with -- generally -- three namespaces available.
At any time during execution, there
are at least three nested scopes whose
namespaces are directly accessible:
the innermost scope, which is searched
first, contains the local names; the
namespaces of any enclosing functions,
which are searched starting with the
nearest enclosing scope; the middle
scope, searched next, contains the
current module's global names; and the
outermost scope (searched last) is the
namespace containing built-in names.
There are two functions: globals
and locals
which show you the contents two of these namespaces.
Namespaces are created by packages, modules, classes, object construction and functions. There aren't any other flavors of namespaces.
In this case, the call to a function named x
has to be resolved in the local name space or the global namespace.
Local in this case, is the body of the method function Foo.spam
.
Global is -- well -- global.
The rule is to search the nested local spaces created by method functions (and nested function definitions), then search global. That's it.
There are no other scopes. The for
statement (and other compound statements like if
and try
) don't create new nested scopes. Only definitions (packages, modules, functions, classes and object instances.)
Inside a class definition, the names are part of the class namespace. code2
, for instance, must be qualified by the class name. Generally Foo.code2
. However, self.code2
will also work because Python objects look at the containing class as a fall-back.
An object (an instance of a class) has instance variables. These names are in the object's namespace. They must be qualified by the object. (variable.instance
.)
From within a class method, you have locals and globals. You say self.variable
to pick the instance as the namespace. You'll note that self
is an argument to every class member function, making it part of the local namespace.
See Python Scope Rules, Python Scope, Variable Scope.