typechecks: just say no! (was Re: Determining Types)

Alex Martelli aleax at aleax.it
Tue Sep 4 17:09:04 CEST 2001


"Emile van Sebille" <emile at fenx.com> wrote in message
news:9n0avh$4jrve$1 at ID-11957.news.dfncis.de...
    ...
> Yes, but if you expect you're going to get a TypeError and program for
that,
> what's the difference if you do a type check first?

The difference is that the TypeError is only raised
when an object is of a type that just *can't* be
used for a given operation -- presumably it violates
some aspect of needed signature-based polymorphism
(or smacks against one of the few places where the
current Python implementation just can't be happy
enough with that -- they're mercifully rare indeed,
e.g. "real" dictionaries are needed in some cases
rather than arbitrary mappings, but not in all, and
there tends to be fewer such arbitrary implementation
based constraints in successive releases).

You just can't get to the exact same spot by
duplicating with your own type-testing the type
testing that Python already performs internally,
quite apart from the fact that performing anything
twice is a Bad Thing in general ("once, and ONLY
once" is best).  So, once again, "getting forgiveness"
(attempting an operation in a try/except block)
proves superior to "getting permission" (trying
to exhaustively test BEFORE the operation for
whatever could make the operation fail -- one
always misses SOME thing or other, or else over-
constrains things by _excessive_ checks, while
try/except is much more robust, simpler, AND
lets whatever testing's actually needed happen
"once, and ONLY once" inside the operation:-).


Alex






More information about the Python-list mailing list