Asked By – Charles Merriam
What exactly are the Python scoping rules?
If I have some code:
code1 class Foo: code2 def spam..... code3 for code4..: code5 x()
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.
Now we will see solution for issue: Short description of the scoping rules?
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.)
Local — Names assigned in any way within a function (
lambda), and not declared global in that function
Enclosing-function — Names assigned in the local scope of any and all statically enclosing functions (
lambda), from inner to outer
Global (module) — Names assigned at the top-level of a module file, or by executing a
globalstatement in a
defwithin the file
Built-in (Python) — Names preassigned in the built-in names module:
So, in the case of
code1 class Foo: code2 def spam(): code3 for code4: code5 x()
for loop does not have its own namespace. In LEGB order, the scopes would be
- L: Local in
- E: Any enclosing functions (if the whole example were in another
- G: Were there any
xdeclared globally in the module (in
- B: Any builtin