An Object's Type

Hrvoje Niksic hniksic at xemacs.org
Thu Dec 6 10:44:00 EST 2007


Bruno Desthuilliers <bruno.42.desthuilliers at wtf.websiteburo.oops.com>
writes:

> So ask yourself: in which way will the final result be different
> from would very probably happens without the "typecheking code" ? In
> *both* cases, you end up with a runtime exception.

The idea behind such type checks is to make sure type errors are
caught as early as possible.  Exceptions caught later, the philosophy
goes, are harder to debug because by then the cause of the problem can
be obscured.  Consider an object of the wrong type passed to a method:
the method can store the object in its own instance attribute, and
keep working on something else.  Then, much later, the faulty object
gets actually used and the error is raised.  By the time the exception
is thrown, you have no idea where the offending object came from.

Personally, I consider the loss in flexibility to outweigh any
benefits of overeager type checks.  Besides, type checks are only one
of the many possible constraints you could check in your objects, yet
proponents of type checks tend to treat them as somehow much more
important or fundamental.

Hopefully Python 3's support for abstract base classes will provide a
standard way to have our cake and eat it by allowing declarative
subtypes.  That way type checks will be possible to prevent accidents,
but without compromising flexibility.  Pure "duck typing" will be made
a bit more verbose, but not impossibly so.



More information about the Python-list mailing list