How can I check if a type is a subtype of a type in Python? I am not referring to instances of a type, but comparing type instances themselves. For example:
class A(object):
...
class B(A):
...
class C(object)
...
# Check that instance is a subclass instance:
isinstance(A(), A) --> True
isinstance(B(), A) --> True
isinstance(C(), A) --> False
# What about comparing the types directly?
SOME_FUNCTION(A, A) --> True
SOME_FUNCTION(B, A) --> True
SOME_FUNCTION(C, A) --> False
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.
The isinstance() function checks if the object (first argument) is an instance or subclass of classinfo class (second argument).
In Python anything that is a type can be subclassed. So we can subclass type itself. >>> class subtype(type): pass. We can now use subtype in pretty much the same way as type itself. In particular we can use it to construct an empty class.
Generally speaking isinstance is a 'more' elegant way of checking if an object is of a certain "type" (since you are aware of the Inheritance chain). On the other hand, if you are not aware of the inheritance chain and you need to be pick, go for type(x) == ...
Maybe issubclass
?
>>> class A(object): pass
>>> class B(A): pass
>>> class C(object): pass
>>> issubclass(A, A)
True
>>> issubclass(B, A)
True
>>> issubclass(C, A)
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With