Class Variable Question
Douglas Alan
nessus at mit.edu
Mon Apr 9 23:25:04 EDT 2001
Carlos Alberto Reis Ribeiro <cribeiro at mail.inet.com.br> writes:
> >I'm not arguing against "programmer freedom". I'm arguing for
> >features that reduce bugs without reducing power.
> That's the point. Because of the way Python works, it is almost impossible
> to implement any kind of "attribute checking". My own code is filled with
> this kind of construct. You can build new classes on the fly, make
> composite objects, a whole lot of things that are nearly impossible to do
> using other statically typed languages.
I'm not arguing that Python should be statically typed. Just that it
is unfortunate that assignment automatically creates new variables.
Creating a new variable and assigning to an existing variable should
have been different operations.
A language that makes you declare a variable before using it doesn't
necessarily eliminate any power at all. It just might make you type
a little bit more. Such extra typing in some cases is surely worth
the extra safety, in my opinion. Especially, since the lack of safety
in this case causes bugs that I see over and over again, and they are
often not always trivial to track down.
In the rare instances in which you want to set a variable even if it
hasn't been created yet, you can do something like this:
try:
set x = 3
except NameError:
let x = 3
> If you really think that this is a good idea (and I understand your
> position for some particular cases), put some checks on the
> __setattr__ of your class. It will trap all occurrences of new
> attributes being attached to the class instance. This is a quick
> example, by no means complete, that shows the concept:
But this doesn't fix the even more serious problem with local
variables. Also my coworkers would kill me if I was doing this kind
of thing on all my classes, and it doesn't help when I have to work on
their code.
|>oug
More information about the Python-list
mailing list