Let's say that I have a class Suit and four subclasses of suit: Heart, Spade, Diamond, Club.
class Suit:
...
class Heart(Suit):
...
class Spade(Suit):
...
class Diamond(Suit):
...
class Club(Suit):
...
I have a method which receives a suit as a parameter, which is a class object, not an instance. More precisely, it may receive only one of the four values: Heart, Spade, Diamond, Club. How can I make an assertion which ensures such a thing? Something like:
def my_method(suit):
assert(suit subclass of Suit)
...
I'm using Python 3.
According to the Python doc, we can also use
class.__mro__
attribute orclass.mro()
method:issubclass
minimal runnable exampleHere is a more complete example with some assertions:
GitHub upstream.
Tested in Python 3.5.2.
issubclass(class, classinfo)
Excerpt:
You can use the builtin issubclass. But type checking is usually seen as unneccessary because you can use duck-typing.
You can use
issubclass()
like thisassert issubclass(suit, Suit)
.