LEGB rule, totally confused ...

Diez B. Roggisch deets at nospam.web.de
Tue Aug 14 09:17:14 EDT 2007


stef mientki wrote:

> hello,
> 
> I've thought many times I finally understood the import / namespace rules,
> but again I'm totally lost :-(
> 
> This is my library file
> 
>     # Module lib_test.py
> 
>     X = 1
> 
>     def Init():
>         global X
>         X = 3
>         print 'Init', X
> 
>     def Run ():
>         print X                 <=== UnboundLocalError: local variable
>     'X' referenced before assignment
>         X = X + 1
>         print ' Run', X
> 
> 
> 
> And this my main program in another file:
> 
>     import lib_test
>     lib_test.Init()
>     print lib_test.X
> 
>     lib_test.Run()
>     print lib_test.X
> 
> Why do I get the error ?
> Printing isn't assigning anything or am I missing something.
> Now if I remove "X = X + 1" I don't get an error ???
> Is this a problem of the traceback procedure or the IDE,
> or is Python not completely an interpreter, that reads line by line ???
> 
> Please explain this to me.

This are the scoping-rules of python. A variable name on the left side of an
name-binding/assignment operator (including augmented assignments, vulgo:
+= and brothers) will make the variable name a function-local.

So 

x = 10
def foo():
   print x
   x = 100

makes x a local variable to foo, which of course can't be accessed in 

print x

Diez



More information about the Python-list mailing list