Spot any errors? let me know, but Unleash your pedant politely please.

Tuesday, 9 June 2009

Python: Finding out if a class is a subclass of a class

I needed to find out whether a class was a subclass of another. Googling, I found a message by Armin Rigo on the Python-Dev mailing list with this line :
    for basecls in type(obj).__mro__:

A quick look squizz at __mro__, enough to see that it represents 'method resolution order'. (I'll look in more details at some point, but that phrase was enough for now). A bit of a distillation at the Python command line, and I end up with this simple test/condition:
    <ParentClass> in <ChildClass>.__mro__

No comments:

Post a Comment