In Python, how can I differentiate between a concrete subclass and a subclass which is still abstract (i.e. not all abstract methods have been implemented)?
Consider the following:
import abc class A(abc.ABC): @abc.abstractmethod def do_something(self): pass class B(A): def do_something(self): print('I am doing') class C(A): pass for subclass in A.__subclasses__(): if is_concrete_class(subclass): subclass().do_something() else: print('subclass is still abstract')
What is the implementation of is_concrete_class
?
I could attempt to instantiate each subclass given by __subclasses__()
and catch TypeError: Can't instantiate abstract class <class_name> with abstract methods <...>
, but TypeError
seems too broad of an exception to catch.
I didn’t find anything useful in Python’s ABC Library.
Advertisement
Answer
There’s a function for that in the inspect
module: inspect.isabstract(some_object)
will tell you whether an object is an abstract class.
It returns True
for an abstract class, and False
for anything else, including abstract methods, classes that inherit from abc.ABC
but are still concrete because don’t have abstract methods, and objects that have nothing to do with abstract classes, like 3
.