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

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

There is a newer version: 4.23.0.17664
Show newest version

This rule raises an issue when operators in and not in are called with a right operand not supporting membership protocol.

Why is this an issue?

Operators in and not in, also called "membership test operators", require that the right operand supports the membership protocol.

In order to support the membership protocol, a user-defined class should implement at least one of the following methods: __contains__, __iter__, __getitem__.

If none of these methods is implemented, a TypeError will be raised when performing a membership test.

How to fix it

Code examples

Noncompliant code example

myint = 42

if 42 in myint:  # Noncompliant: integers don't support membership protocol
    ...

class A:
    def __init__(self, values):
        self._values = values

if "mystring" in A(["mystring"]):  # Noncompliant: class A doesn't support membership protocol
    ...

Compliant solution

mylist = [42]

if 42 in mylist:
    ...

class MyContains:
    def __init__(self, values):
        self._values = values

    def __contains__(self, value):
        return value in self._values

if "mystring" in MyContains(["mystring"]):
    ...

# OR

class MyIterable:
    def __init__(self, values):
        self._values = values

    def __iter__(self):
        return iter(self._values)

if "mystring" in MyIterable(["mystring"]):
    ...

# OR

class MyGetItem:
    def __init__(self, values):
        self._values = values

    def __getitem__(self, key):
        return self._values[key]

if "mystring" in MyGetItem(["mystring"]):
    ...

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy