[Python-Dev] Evil isinstance()

Guido van Rossum guido@python.org
Sun, 31 Mar 2002 16:13:48 -0500


> What I recommend, FWIW, until and unless PEP 246 eventuates
> and makes the world wonderful:
> 
> # if there's a specifically relevant special-method, such as __int__ is for
> # int(), you can of course first try getting thearg.__int__ -- if that
> # fails, or if nothing that relevant applies, you can then proceed with
> # something along the lines of:
> 
> try: thearg+''
> except TypeError: pass
> else:
>     "do the stringlike case here"
> 
> try: thearg+0
> except TypeError: pass
> else:
>     "do the numberlike case here"

I'm vaguely unhappy with catching exceptions here -- there might be
side effects, and they may mask bugs in user-defined classes that try
to implement __add__ (especially since TypeError is a common symptom
of a bug).

> Why would you want your function to break if called with an instance
> of UserString, say, or a user-defined number type?  Smooth
> polymorphism is high on the list of Python's strong points -- why
> break it, when you can preserve this excellent quality?

I'm for this; but it's hard to pick the right test in many cases.
Many types define both __str__ and __int__ -- but either may lose
information (in the case of a float, these *both* lose information!).

This leaves me in the uncomfortable position that I don't know what to
recommend. :-(

--Guido van Rossum (home page: http://www.python.org/~guido/)