LEGB rule, totally confused ...

Laurent Pointal laurent.pointal at limsi.fr
Tue Aug 14 09:20:30 EDT 2007


stef mientki a écrit :
> 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.

If you use a global to *modify* it, you MUST declare "global X", either 
Python consider using a local.
So for your error: at compile time, in Run(), it see that it must use a 
local X (because you set it) and generate ad-hoc bytecode, but when 
running X is not defined locally, so the error.

> Now if I remove "X = X + 1" I don't get an error ???

If you remove the "X =..." statement, then the compiler dont know 
a-priori if its local or global, so it search X in both namespaces.

> Is this a problem of the traceback procedure or the IDE,
> or is Python not completely an interpreter, that reads line by line ???

Its compiled to buyte-code then interpreted from the byte-code.

> 
> Please explain this to me.
> 
> thanks,
> Stef Mientki

A+

Laurent.



More information about the Python-list mailing list