The Python Oracle

How do I check (at runtime) if one class is a subclass of another?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Question
00:53 Accepted answer (Score 301)
01:07 Answer 2 (Score 59)
01:26 Answer 3 (Score 33)
01:50 Answer 4 (Score 26)
02:08 Thank you

--

Full question
https://stackoverflow.com/questions/4912...

Answer 1 links:
[issubclass(class, classinfo)]: http://docs.python.org/library/functions...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #subclass #assert

#avk47



ACCEPTED ANSWER

Score 325


You can use issubclass() like this assert issubclass(suit, Suit).




ANSWER 2

Score 62


issubclass(class, classinfo)

Excerpt:

Return true if class is a subclass (direct, indirect or virtual) of classinfo.




ANSWER 3

Score 34


You can use isinstance if you have an instance, or issubclass if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.




ANSWER 4

Score 28


The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup.