[Python-Dev] Evil isinstance() (original) (raw)

Alex Martelli aleax@aleax.it
Sun, 31 Mar 2002 22:29:44 +0100


On Sunday 31 March 2002 23:13, Guido van Rossum wrote: ...

> 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).

Good point, but... if a user-defined class raises TypeError when I try to add 0 to an instance thereof, then I can't use said instance as a number... whether because of a bug in said class, or because said class is not intended to be number-like, I can't use it, so I won't. I will then similarly discover I can't use it as a string either, and end up by raising TypeError because by hypothesis I don't know what else to do.

This doesn't seem so much of a problem to me to warrant rejecting perfectly good numberlike and stringlike classes' instances, by isinstance'ing away.

If a user-defined class is coded to have side effects on add, I think any attempt to use instances of that class is doomed to produce weird effects. By that token, the user could subclass int (so isinstance passes) and still do weird things in any overridden method, so I think this is a case of "against stupidity, the god themselves struggle in vain" and would not lose sleep over it.

> 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.

Oh yes, definitely.

Many types define both str and int -- but either may lose information (in the case of a float, these both lose information!).

Every subclass of object has str, so having it supplies no information (of any practical usefulness) about the class.

int may well lose information -- that's how it's defined, after all -- but having it might be taken as one possible test of numberhood

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

In your shoes, I'd recommend PEP 246 -- since, if I were in your shoes, I'd have approved it long ago. (We don't need to have interfaces as a distinct concept from types/classes to approve PEP 246 -- any types can serve as 'protocols' to make PEP 246 a reality). It would offer a very good solution to problems in this category, in my opinion.

Alex