All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S5722.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

This rule raises an issue when a special method is defined with an unexpected number of parameters.

Why is this an issue?

Python allows developers to customize how code is interpreted by defining special methods (also called magic methods). For example, it is possible to override how the multiplication operator (a * b) will apply to instances of a class by defining in this class the __mul__ and __rmul__ methods. Whenever a multiplication operation is performed with this class, the Python interpreter will call one of these methods instead of performing the default multiplication.

Each special method expects a specific number of parameters. The Python interpreter will call these methods with those parameters. Calls to a special method will throw a TypeError if it is defined with an incorrect number of parameters.

How to fix it

Make sure to use the same signature defined in the Python documentation for each special methods.

Code examples

Noncompliant code example

class A:
    def __mul__(self, other, unexpected):  # Noncompliant: too many parameters
        return 42

    def __add__(self):  # Noncompliant: missing one parameter
        return 42

A() * 3  # TypeError: __mul__() missing 1 required positional argument: 'unexpected'
A() + 3  # TypeError: __add__() takes 1 positional argument but 2 were given

Compliant solution

class A:
    def __mul__(self, other):
        return 42

    def __add__(self, other):
        return 42

A() * 3
A() + 3

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy