Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list the inherited abstractmethods of an abstract subclass in Python?

Tags:

python

oop

How can I see the attributes inherited by an abstract class subclassing from another?

For example:

class MammalAbstract(ABC):

    @abstractmethod
    def legs(self):
        pass

class CanineAbstract(MammalAbstract):

    @abstractmethod
    def tail(self):
        pass

class PekineseAbstract(CanineAbstract):
    
    @abstractmethod
    def yip(self):
        pass

So Canine instances must have legs and tail, and Pekinese additionally yip.

Is there any way to get the PekineseAbstract and see what attributes it must expose, including those it inherits? Or is the only thing to do for readability to repeat the abstractmethods inherited?

As I understand it, one point of abstract classes is to clarify code by providing a contract that can be inspected to see what attributes a class must expose. But if these code blocks are scattered over several files, a reader has to find and read all those files to know what a Canine or a Pekinese must support.

I looked at inspect but it doesn't have anything handy, though maybe has the tools to build something that does this.

like image 359
tlskr Avatar asked Dec 19 '25 15:12

tlskr


1 Answers

You can walk the class’s method resolution order (MRO) and collect all methods marked with __isabstractmethod__:

from abc import ABC, abstractmethod

def get_abstract_method_origins(cls):
    result = {}
    for base in reversed(cls.__mro__):  # start from root class
        for name, attr in base.__dict__.items():
            if getattr(attr, "__isabstractmethod__", False):
                result.setdefault(name, base.__name__)
    return result
#USAGE:
print(get_abstract_method_origins(PekineseAbstract))
  • abc.ABCMeta populates the __abstractmethods__ attribute by walking the MRO.

  • Abstract methods are just regular functions marked with __isabstractmethod__ = True.

  • By checking each class’s __dict__, we avoid accidentally picking up overridden methods.

  • setdefault() ensures we only record the first (i.e., original) definition.

So no, you don't need to repeat abstract methods for readability — Python's ABC machinery already collects them, and with the __abstractmethods__ attribute (or the helper function above), you can see the full contract clearly.

like image 87
Daniel Raphael Avatar answered Dec 21 '25 08:12

Daniel Raphael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!