annoying behavior

Patrick Maupin pmaupin at speakeasy.net
Tue Sep 28 23:15:20 EDT 2004


<elbertlev at hotmail.com> wrote:
> 
> Jeremy!
> 
> Sure it would be nice if a the interpreter would give a warning before
> really instantiating the instance of class foo (at least in "debug" mode).
> In my case the error happened after the program ran about 30 minutes. I do
> not think this is impossible.

But, in Python, instances are "open".  This means that I can add
attributes to a class instance at _any_ time (well, if I don't use
__slots__).  The classes are open, too.  I could even add attributes
to the class definition, after import, and before creating any
instances of the class.

This openness allows for the creation of some really powerful
programs.  It also allows for the creation of some really powerful
bugs, which is why you are being admonished to run unit tests.

One thing this openness makes very difficult is the sort of static
semantic check you seem to think the compiler should perform.  If I
can add a variable to the class after I import it but before I
instantiate it, how would a checker know if it was a bug or not? 
(This is not to say that there are not programs which can flag such
constructs as "suspect", and you are certainly free to use such
programs to improve your own code, but please don't attempt to foist
the rigors of a statically declared language on Python -- a lot of its
practitioners are escapees from such rigorous straightjackets.)

One quasi-rhetorical question, though -- I haven't used C++ in awhile
(and I've never used Java).  Are the stock compilers actually powerful
enough to flag this sort of inter-method use of an instance member
variable before it has been initialized?  If so, color me edified.  If
not, why are you complaining that Python didn't find this soon enough,
rather than praising Python for finding it at all?  Personally, I
would much rather debug from such a clean description of what went
wrong than go rummaging around the typical core dump you could get
from an uninitialized pointer in another language.

Regards,
Pat



More information about the Python-list mailing list