Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isinstance() and issubclass() return conflicting results

How do you explain isinstance(Hello,object) returns True whilst issubclass(Hello,object) returns False?

>>> class Hello:     pass 

and

>>> isinstance(Hello,object) True >>> issubclass(Hello,object) False >>> a = Hello() >>> isinstance(a,object) True 
like image 327
Tarik Avatar asked Nov 12 '11 20:11

Tarik


People also ask

What is the difference between Isinstance and Issubclass?

isinstance() and issubclass() The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).

What is the purpose of Issubclass and Isinstance function of Python?

isinstance() checks whether or not the object is an instance or subclass of the classinfo. Whereas, issubclass() only check whether it is a subclass of classinfo or not (not check for object relation).

What does Isinstance mean in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.

Is Isinstance fast?

The isinstance() function is faster than the type function. We can compare both their performance by using the timeit library. As you can see, the isinstance() function is 30 times faster than type() function.


2 Answers

The accepted answer is correct, but seems to miss an important point. The built-in functions isinstance and issubclass ask two different questions.

isinstance(object, classinfo) asks whether an object is an instance of a class (or a tuple of classes).

issubclass(class, classinfo) asks whether one class is a subclass of another class (or other classes).

In either method, classinfo can be a “class, type, or tuple of classes, types, and such tuples.”

Since classes are themselves objects, isinstance applies just fine. We can also ask whether a class is a subclass of another class. But, we shouldn't necessarily expect the same answer from both questions.

class Foo(object):     pass  class Bar(Foo):     pass  issubclass(Bar, Foo) #>True isinstance(Bar, Foo) #>False 

Bar is a subclass of Foo, not an instance of it. Bar is an instance of type which is a subclass of object, therefore the class Bar is an instance of object.

isinstance(Bar, type) #>True issubclass(type, object) #>True isinstance(Bar, object) #>True 
like image 115
cbare Avatar answered Sep 25 '22 14:09

cbare


It's because you are using old-style classes so it doesn't derive from object. Try this instead:

class Hello(object):     pass  >>> issubclass(Hello,object) True 

Old-style classes are deprecated and you shouldn't use them any more.

In Python 3.x all classes are new-style and writing (object) is no longer required.

like image 20
Mark Byers Avatar answered Sep 25 '22 14:09

Mark Byers