Incompatible new and init
ID |
python.incompatible_new_init |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Python |
Tags |
reliability, suspicious-construct |
Description
Reports classes where new and init take different non-implicit parameters. Python calls both with the same arguments at instantiation time, so the call site needs a single argument list that satisfies both signatures; if the two methods do not agree, the resulting TypeError surfaces at the first construction.
class Bad:
def __new__(cls, x):
return super().__new__(cls)
def __init__(self, x, y): # FLAW — extra y not in __new__
self.x = x
self.y = y
class Good:
def __new__(cls, x, y):
return super().__new__(cls)
def __init__(self, x, y): # OK
self.x = x
self.y = y
Rationale
The pair new / init is one of Python’s data-model contracts that is easy to break and silent until runtime. Static detection turns the hidden mismatch into a code-review item.
The rule compares parameter names after dropping the implicit first argument (cls for new, self for init); args/*kwargs shapes are flagged when one side has them and the other does not.
Remediation
Make the parameter lists agree, or override only init and let object.new handle construction.
References
-
https://docs.python.org/3/reference/datamodel.html#object.new[Python — object.new]
-
https://docs.python.org/3/reference/datamodel.html#object.init[Python — object.init]