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

Skip Montanaro skip at pobox.com
Mon Sep 3 20:59:18 EDT 2001


    Emile> "Skip Montanaro" <skip at pobox.com> wrote in message
    Emile> news:15251.48786.329817.450337 at localhost.localdomain...
    >> 
    Emile> Couldn't you always coerce it?
    Emile> str('hello')
    Emile> str(123)

    >> Yes, I could, but the problem arises quite rarely.  It seems to me
    >> that checking the type is going to generally be faster than always
    >> coercing.

I suppose it might be the way you've written it, but I don't actually call
an extra function to perform the comparison.  I just code the test inline:

    if type(var) is not types.StringType:
        var = str(var)

Maybe that is still slower than always executing

    var = str(var)

I've never bothered to test it.  Remember, this will *only* be true for me
once in a very rare while when a perl client receives an input string (band
or venue name) that happens to be all digits.  It almost never happens.
Compared to the real work the routine is doing (pulling data out of a MySQL
database, for example), this would be such a trivial micro-optimization that
I'd never notice it.  I could also speed it up by some trivial amount by
importing types as

    from types import *

but I prefer the more explicit notation.

Skip





More information about the Python-list mailing list