Re: Non-symmetric access

Guido.van.Rossum@cwi.nl
Thu, 18 Aug 1994 10:16:00 +0200

> Here's a case where variable reference and variable assignments are
> non-symmetric:
>
> class a: # give a unique integer ID to all instances
> i = 1 # class variable
> def __init__(self):
> self.j = self.i # instance variable <-- class variable
> self.i = self.i + 1 # modify class variable (?)
>
> Does the last statement modify the class variable or not?
> No. Here's a sample run:
>
> >>> a1 = a() --> <instance...>
> >>> a2 = a() --> <instance...>
> >>> a1.__dict__ --> {j:1, i:2}
> >>> a2.__dict__ --> {j:1, i:2}
> >>> a.i --> 1
>
> Is this a good thing, or bad?

Some call it a bug, others a feature. I call it a fact of Pythonic
life :-)

In general, in Python, for references, the interpreter is willing to
do a search of a number of name spaces (e.g. local - global -
built-in, or instance - class - base classes), but for assignments,
the new value goes into the closest name space. The reason is that
Python doesn't have variable declarations, so assignment is the only
way to define a variable.

As a matter of principle, assignments go into the closes name space
unless this is explicitly overridden (by using the "global" statement
for plain variables, by using the class name for class/instance
attributes). This is done because in general local variables are used
more often than globals -- defaulting to global (as Perl does) would
mean that the average program would have to have a lot of 'local'
declarations, while currently most programs get by without a single
'global' declarations.

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>