[Python-Dev] Should issubclass() be more like isinstance()? (original) (raw)

Crutcher Dunnavant crutcher at gmail.com
Wed Apr 5 05🔞39 CEST 2006


On 4/4/06, Guido van Rossum <guido at python.org> wrote:

On 4/4/06, Crutcher Dunnavant <crutcher at gmail.com> wrote: > On 4/4/06, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote: > > Crutcher Dunnavant wrote: > > > > > A) issubclass() throws a TypeError if the object being checked is not > > > a class, which seems very strange. > > > > If I ever pass a non-class to issubclass() it's almost > > certainly a bug in my code, and I'd want to know about > > it. > > Perhaps, but is it worth distorting a predicate?

Certainly. In other languages this would be a compile-time error.

In other, statically typed languges. Someone hands me X, I want to know if X is a subclass of Y. Yes or No. If X is not a class, then it is not a subclass of Y, hence issubclass(X, Y) should return False.

There's no rule that predicate cannot raise an exception.

No, but it makes many applications (such as using it as a test in list comprehensions) difficult enough to not be worth it.

If you're not sure whether something is a class or not, you should first sniff it out for its class-ness before checking whether it's a subclass of something. I recommend hasattr(x, "bases") which is more likely to recognize classes than isinstance(x, type) -- the latter only works for standard new-style classes.

> > On the rare occasions when I don't want this, I'm > > happy to write > > > > isinstance(c, type) and issubclass(c, d) > > This doesn't work, did you mean? > isinstance(c, types.ClassType) and issubclass(c, d) > > > > > B) issubclass() won't work on a list of classs, > > > the way isinstance() does. > > > > That sounds more reasonable. I can't think of any > > reason why it shouldn't work. Agreed. -- --Guido van Rossum (home page: http://www.python.org/~guido/)

-- Crutcher Dunnavant <crutcher at gmail.com> littlelanguages.com monket.samedi-studios.com



More information about the Python-Dev mailing list