Search code examples
pythoninheritancepolymorphism

How to flag a method to be required to overload when inheriting in Python?


I want to tell the future programmer the following class methods must be overridden if the AbstractCrawler is inherited.

class AbstractCrawler(object):

    def get_playlist_videos():
        pass

    def get_related_videos():
        pass

    def create_playlists():
        pass

Solution

  • You can mark the class and its methods as abstract:

    from abc import ABC, abstractmethod
    
    class AbstractCrawler(ABC):
        @abstractmethod
        def get_playlist_videos(self):
            pass
    
        @abstractmethod
        def get_related_videos(self):
            pass
    
        @abstractmethod
        def create_playlists(self):
            pass
    

    Then:

    class ImplCrawler(AbstractCrawler):
        pass
    
    >>> i = ImplCrawler()
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    TypeError: Can't instantiate abstract class ImplCrawler with abstract methods create_playlists, get_playlist_videos, get_related_videos
    

    Compared to:

    class ImplCrawler(AbstractCrawler):
        def get_playlist_videos(self):
            pass
    
        def get_related_videos(self):
            pass
    
        def create_playlists(self):
            pass
    
    >>> i = ImplCrawler()
    # No error