Search code examples
pythonabstract-classsignature

should abstract class return same type as expected implemented method?


I am using Python abc package to declare abstract classes. When I define an abstract method, should I return an empty object with same type as expected or simply pass?enter image description here

MWE:

import abc


class A(abc.ABC):
    @abc.abstractmethod
    def method_1(self):
        """
        This abstract method should return a list
        """
        pass

    def method_2(self):
        list_output_method_1 = self.method_1()
        for x in list_output_method_1:
            pass

Doing so, PyCharm warns me in method_2 about non iterable list_output_method_1.

Should I put a return [] in method_1 instead?


Solution

  • You can update your docstring in method1 by setting the return type to list.

    import abc
    
    class A(abc.ABC):
        @abc.abstractmethod
        def method_1(self):
            """
            This abstract method should return a list
            :rtype: list
            """
            pass
    
        def method_2(self):
            list_output_method_1 = self.method_1()
            for x in list_output_method_1:
                pass