Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply.)
LEGB Rule
Local — Names assigned in any way within a function (
def
orlambda
), and not declared global in that functionEnclosing-function — Names assigned in the local scope of any and all statically enclosing functions (
def
orlambda
), from inner to outerGlobal (module) — Names assigned at the top-level of a module file, or by executing a
global
statement in adef
within the fileBuilt-in (Python) — Names preassigned in the built-in names module:
open
,range
,SyntaxError
, etc
So, in the case of
code1
class Foo:
code2
def spam():
code3
for code4:
code5
x()
The for
loop does not have its own namespace. In LEGB order, the scopes would be
- L: Local in
def spam
(incode3
,code4
, andcode5
) - E: Any enclosing functions (if the whole example were in another
def
) - G: Were there any
x
declared globally in the module (incode1
)? - B: Any builtin
x
in Python.
x
will never be found in code2
(even in cases where you might expect it would, see Antti’s answer or here).