[Tutor] is this a bug global i ???

Kent Johnson kent37 at tds.net
Tue Jun 14 12:16:05 CEST 2005


Pujo Aji wrote:
> I have code like this:
> 
> class A:
>   def __init__(self,j):
>     self.j = j
>   
>   def something(self):
>     print self.j
>     print i            # PROBLEM is here there is no var i in class A
> but it works ???
> 
> if __name__ == '__main__':
>   i = 10
>   a = A(5)
>   a.something()
> 
> I don't define global i but it will takes var i from outside of class A.

This is normal behavior. When Python needs to resolve a bare name it looks it up first in the local scope (the current function), then in any enclosing lexical scopes (for nested functions), then the global scope and finally the builtins. In this case the binding for i is found in the global scope.

Note that *assigning* to a name always happens in the local scope unless the name is declared global. There is no (clean) way to assign to a name in an enclosing lexical scope or the builtins.

These might help a little:
http://docs.python.org/tut/node11.html#SECTION0011200000000000000000
http://docs.python.org/ref/naming.html

Kent



More information about the Tutor mailing list