It is a good practice that a method of a subclass has the same signature as the corresponding method of the base class. If one violates this principle, PyCharm gives the warning:
Signature of method does not match signature of base method in class
There is (at least) one exception to this principle: the Python initialisation method __init__
. It is common that child classes have different initialisation parameters than their parent classes. They may have additional parameters, or they may have less parameters, usually obtained by using a constant value for the parameter of the parent class.
Since Python does not support multiple initialisation methods with different signatures, a Pythonic way of having different constructors are so-called factory methods (see e.g: https://stackoverflow.com/a/682545/10816965).
PyCharm thinks that these factory methods are no exceptions to the principle that methods of subclasses should have the same signature as their corresponding parent classes. Of course, I could ignore these warnings - since these factory methods are similar to __init__
or __new__
, I think one could take the position that these warnings are misplaced.
However, I wondered whether I miss something here and my coding style is not best practice.
So my question is: Is this an unintended behavior of PyCharm, or is there indeed a more Pythonic way for this pattern?
class A:
@classmethod
def from_something(cls, something):
self = cls()
# f(self, something)
return self
def __init__(self):
pass
class B(A):
@classmethod
def from_something(cls, something, param): # PyCharm warning:
# Signature of method 'B.from_something()' does not match
# signature of base method in class 'A'
self = cls(param)
# g(self, something, param)
return self
def __init__(self, param):
super().__init__()
self.param = param
class C:
@classmethod
def from_something(cls, something, param):
self = cls(param)
# f(self, something, param)
return self
def __init__(self, param):
self.param = param
class D(C):
@classmethod
def from_something(cls, something): # PyCharm warning: Signature of
# method 'D.from_something()' does not match signature of base
# method in class 'C'
self = cls()
# g(self, something)
return self
def __init__(self):
super().__init__(None)