Wrong number of arguments in a class instantiation¶
ID: py/call/wrong-number-class-arguments Kind: problem Severity: error Precision: very-high Tags: - reliability - correctness - external/cwe/cwe-685 Query suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
A call to the
__init__ method of a class must supply an argument for each parameter that does not have a default value defined, so:
The minimum number of arguments is the number of parameters without default values.
The maximum number of arguments is the total number of parameters, unless the class
__init__method takes a varargs (starred) parameter in which case there is no limit.
If there are too few arguments then check to see which arguments have been omitted and supply values for those.
If there are too many arguments then check to see if any have been added by mistake and remove those.
Also check where a comma has been inserted instead of an operator or a dot. For example, the code is
obj,attr when it should be
If it is not clear which are the missing or surplus arguments, then this suggests a logical error. The fix will then depend on the nature of the error.
class Point(object): def __init__(self, x, y): self.x = x self.y = y p = Point(1) # TypeError: too few arguments p = Point(1,2,3) # TypeError: too many arguments
Python Glossary: Arguments.
Python Glossary: Parameters.
Python Programming FAQ: What is the difference between arguments and parameters?.
The Python Language Reference: Data model: object.init
The Python Tutorial: Classes
Common Weakness Enumeration: CWE-685.