isinstance() and issubclass() return conflicting results
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
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.