What exactly are the Python scoping rules?
If I have some code:
code1 class Foo: code2 def spam..... code3 for code4..: code5 x()
Where is x found? Some possible choices include the list below:
- In the enclosing source file
- In the class namespace
- In the function definition
- In the for loop index variable
- Inside the for loop
Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?
There must be a simple reference or algorithm somewhere. It’s a confusing world for intermediate Python programmers.
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 (
deforlambda), and not declared global in that functionEnclosing-function — Names assigned in the local scope of any and all statically enclosing functions (
deforlambda), from inner to outerGlobal (module) — Names assigned at the top-level of a module file, or by executing a
globalstatement in adefwithin the fileBuilt-in (Python) — Names preassigned in the built-in names module:
open,range,SyntaxError, etcSo, in the case of
The
forloop does not have its own namespace. In LEGB order, the scopes would bedef spam(incode3,code4, andcode5)def)xdeclared globally in the module (incode1)?xin Python.xwill never be found incode2(even in cases where you might expect it would, see Antti’s answer or here).