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

Guido van Rossum guido@python.org
Sun, 31 Mar 2002 17:19:55 -0500


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.

But hiding the true source of the error. If there was a bug in the user code, I'd like to hear about that, not about your inability to deal with it. Otherwise, why don't you just use a bare "except:" clause ?

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.

Agreed, and I think the solution ought to be sought in asking a question involving hasattr().

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

Unfortunately, non-numeric types are known to implement int for some obscure purpose.

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

Maybe you can summarize it again using a different vocabulary? I find that PEP very hard to read, but I recall liking your informal explanation of it. Unfortunately I don't recall enough of that explanation to go ahead and approve the PEP (I have no idea what effect that would have).

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