Bug or feature?

Donn Cave donn at u.washington.edu
Fri May 14 13:39:50 EDT 1999


"Gregory A. Landrum" <landrum at foreman.ac.rwth-aachen.de> writes:
...
| I was stupidly assuming that a variable initialized in the class scope
| would act the same way as a variable initialized within the __init__
| method.  So I figured I could initialize things which are going to have
| default values outside of the __init__ method and thus (I thought) make
| the code a little bit easier to read.  I'm still not totally clear on why
| this isn't the case, but I can live with knowing that "it is true."

I think this really may be a useful thing to understand, because it's
not peculiar to "class", at its root, it's a basic design property of
the language that shows up in other places and is just as surprising
there if you don't get it.

Who has been reading this list for a while and has never seen someone
ask ``why didn't this assignment to a global variable work?''

   x = 0
   def g():
       x = 1

   print x
   g()
   print x

Does this problem look familiar?

An assigment in Python binds an object to a reference name, and that
name is stored in a "namespace" associated with some program scope.
The name may be new - that is, Python doesn't require that you declare
a variable separately before it's instantiated with a value.  Clearly
this means that the new name should go in the innermost scope's
namespace, that is, we automatically create a function-local variable.
As a point of faith, clearly we automatically create a local variable
whether or not there's any such name in an enclosing scope, because
we prefer a function to be reasonably independent of its environment.

Now the present case of the class namespace in "self" looks exactly
the same to me - "self" is actually an instance namespace enclosed
in class namespaces.  An assignment binds in the innermost instance
namespace, but if you only look and don't touch, you can see the
the outer class namespaces.

I think class data attributes make perfect sense.  Accessed through
"self", they obviously have to be seen as constants, but they can
be modified directly through the class.  It's an appropriate scope
and model for class globals, especially considering the support
for inheritance.

By the way, I have heard that C++ has added "namespace" to its
amazing repertoire, but what it means there I have no idea.  Hope
there's no confusion in it.  I have found the intro/tutorial
documentation in Python a little weak on namespaces and references,
considering the radical role they play in the language - I mean,
take away scope and storage semantics from a language and what's left?

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu




More information about the Python-list mailing list