Inheritance: change signature of child methods

Viewed 3406

I try to figure out what is the best practice in Python inheritance principles, when there is a 'bad idea' to change method signature in a child.

Let's suppose we have some base class BaseClient with already implemented create method (and some abstract ones) that fits good for almost all 'descendants' except one:

 class BaseClient(object):

     def __init__(self, connection=None):
         pass

     def create(self, entity_id, data=None):
         pass

 class ClientA(BaseClient):
     pass

 class ClientB(BaseClient):
     pass

The only class ClientC needs another implementation of create method with a little bit another method signature

 class ClientC(BaseClient):
     ....
     def create(self, data):
         pass

So the question is how to make this in a more 'pythonic' way, taking into account best python practice? Of course we can use *args, **kwargs and other **kwargs-like approaches in parent (child) method, but I'm afraid it makes my code less readable (self-documented).

3 Answers

The answer to "can I change signature of child methods?" is yes, nonetheless it is very bad practice.

The children function overriding the parents class must have the same signature, if you want to be SOLID and not violating the LSP.

The example above:

class BaseClient:
    def create(self, entity_id, data=None):
        pass


class EntityBasedClient(BaseClient):
    def create(self, entity_id, data=None):
        pass


class DataBasedClient(BaseClient):
    def create(self, data):
        pass

Is violating the principle and would also raise a linter warning ("Parameters differ from overridden 'create' method")

Also raising a RedudantInformationError, as proposed by @Sanitiy to keep the consistency of the signature, is still violating the principle, as the parent-method would have a different behaviour if used in place of the child-method.

Take a look also at: Python Method overriding, does signature matter?

Related