Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a type is a subtype of a type in Python?

Tags:

python

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
like image 209
Willi Ballenthin Avatar asked Apr 09 '13 02:04

Willi Ballenthin


People also ask

How do you check if something is a certain type 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.

Does Isinstance check subclass?

The isinstance() function checks if the object (first argument) is an instance or subclass of classinfo class (second argument).

What is a subtype in Python?

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.

Is Isinstance the best way to check types?

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


1 Answers

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
like image 173
DSM Avatar answered Oct 21 '22 09:10

DSM