Willi Ballenthin
Willi Ballenthin

Reputation: 6604

How can I check if a type is a subtype of a type in 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

Upvotes: 32

Views: 21584

Answers (1)

DSM
DSM

Reputation: 353009

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

Upvotes: 55

Related Questions