4

The class Parent has an abstract method and I need to use a different number and types of arguments in the method in the children classes/methods.

from abc import ABC, abstractmethod


class Parent(ABC):
    """Parent"""
    @abstractmethod
    def method(self, *args):
        """method"""


class Child1(Parent):
    """Child1"""
    def method(self, arg1: int):
        print(arg1)


class Child2(Parent):
    """Child2"""
    def method(self, arg1: str, arg2: dict):
        print(arg1, arg2)

For this code pylint is showing me next warning:

[W0221(arguments-differ), Child1.method] Parameters differ from overridden 'method' method

Is it possible to solve the pylint warning and continue using different arguments in children classes? I don't want to use *args in children methods.

pyjedy
  • 389
  • 2
  • 9
  • 6
    If the methods take different arguments you're breaking Liskov Substitution Principle. Pylint is correctly marking your method as bad style. – flakes May 22 '21 at 18:10
  • A caller that's trying to use the `Parent` interface you've defined will find that it doesn't actually work in either `Child` implementation. This is not simply bad code, it is malicious code. Linters exist specifically to help people not write code like this -- if you want to write intentionally evil code, you don't want to be using a linter. – Samwise May 22 '21 at 18:51
  • Thanks for the clarification, this pattern is incorrect and incompatible with pylint. – pyjedy May 23 '21 at 14:56
  • @Samwise What's the alternative then? Should you *never* use abstractmethods if you have child classes with different types of input? Such a parent class seems like a good place to define commonalities of your classes. – Justin P. Feb 01 '22 at 17:10
  • 1
    The point of an abstract parent class is to define a common interface that you can use without knowing anything about the concrete implementation. This is the exact opposite of that -- there is no common interface, and you absolutely have to know which implementation you have in order to use the class correctly. There is no reason for `Parent` to exist in this scenario other than attempting to confuse someone who's trying to figure out the code. – Samwise Feb 01 '22 at 17:11
  • To put it another way: *what commonalities*? – Samwise Feb 01 '22 at 17:17

0 Answers0