Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance: change signature of child methods

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).

like image 234
machin Avatar asked Oct 29 '22 04:10

machin


1 Answers

I'd say, just add the parameter back as keyword with default value None. Then raise an error that explains that some of the input data is lost.

 class ClientC(BaseClient):
 ....
     def create(self,entity_id=None, data):
         if entity_id:
             raise RedudantInformationError("Value for entity_id does nothing")
         pass

This way whenever a programmer tries to handle child C like the other childs, he'll get a warning reminding him, which however he can easily by-step by using the try-Syntax.

like image 102
Sanitiy Avatar answered Nov 15 '22 07:11

Sanitiy