Charles Merriam Charles Merriam - 2 months ago 14
Python Question

Short Description of Scoping Rules

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 above:


  1. In the enclosing source file

  2. In the class namespace

  3. In the function definition

  4. In the for loop index variable

  5. 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.

Answer

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.

L, Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function.

E, Enclosing function locals — Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer.

G, Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.

B, Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,...

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 the current def.

E : Enclosed function, any enclosing functions (if def spam was in another def)

G : Global. Were there any declared globally in the module?

B : Any builtin x() in Python.