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

Alex Martelli aleax at aleax.it
Mon Sep 3 07:02:54 EDT 2001


"Adonis Vargas" <deltapigz at telocity.com> wrote in message
news:fe9k7.1835$ix.446807 at newsrump.sjc.telocity.net...
> how am i able to determine types of variables? i have come up with the

Be aware that, MOST times you THINK you need to typecheck, you
really *don't*.  Type-checks break the wonderful signature based
polymorphism that is the key to so much of Python's power and
simplicity.  Check out the Cookbook recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291
for a way to avoid type-checking (in favour of signature
checking) even when you might think it's indispensable.

That much being said, the built-in function isinstance is the
least painfully horrible way to do typechecking anyway:

def sometypechecking(anobject):
    if isinstance(anobject, type('')):
        print "it's a string"
    elif isinstance(anobject, type(0)):
        print "it's an int"
    elif isinstance(anobject, type(0.0)):
        print "it's a float"
    else:
        print "it's something else"

You can do it in other ways, such as testing if
    type(anobject) is type('')
and so on, but there is really no advantage to those other
ways -- they just damage polymorphic behavior even worse
than isinstance-based checks do (no observable difference
in Python 2.1, but in Python 2.2 it will be possible to
inherit from built-in types: such inheriting objects will
pass an isinstance-based check, but fail a type-is-type
based check, which only checks *identity of types* and NOT
subclassing-relationships).

To summarize: don't type check.  If you think you must,
use "accurate look-before-you-leap" instead.  If you STILL
think you must, use isinstance.  *AND* lobby for the
"protocol-adaptation PEP", the "Object Adaptation" PEP 246,
http://python.sourceforge.net/peps/pep-0246.html, which, if
it's ever adopted in Python, would offer "one obviously right
way" to handle most situations in which people tend to
erroneously think type-checks are the best solution.


Alex






More information about the Python-list mailing list