Scoping in Python – The LEGB Rule

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 orlambda), form 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 it’s own namespace. It would look in the LEGB order,

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.

 

 

source- stackoverflow

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s