The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3

--

Chapters
00:00 How Do I Check (At Runtime) If One Class Is A Subclass Of Another?
00:32 Answer 1 Score 62
00:48 Accepted Answer Score 325
00:58 Answer 3 Score 34
01:14 Answer 4 Score 28
01:26 Thank you

--

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

--

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.