This rule raises an issue when an item operation is performed on an object which doesn’t have the corresponding method.

Why is this an issue?

Getting, setting and deleting items using square brackets requires the accessed object to have special methods:

Performing these operations on an object that doesn’t have the corresponding method will result in a TypeError.

To fix this issue, make sure that the class for which you are trying to perform item operations implements the required methods.

Code examples

Noncompliant code example

del (1, 2)[0]  # Noncompliant: tuples are immutable
(1, 2)[0] = 42  # Noncompliant
(1, 2)[0]

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

a = A([0,1,2])

a[0]  # Noncompliant
del a[0]  # Noncompliant
a[0] = 42  # Noncompliant

class B:
    pass

B[0]  # Noncompliant

Compliant solution

del [1, 2][0]  # Lists are mutable
[1, 2][0] = 42
[1, 2][0]

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

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

    def __setitem__(self, key, value):
        self._values[key] = value

    def __delitem__(self, key):
        del self._values[key]

a = A([0,1,2])

a[0]
del a[0]
a[0] = 42

class B:
    def __class_getitem__(cls, key):
        return [0, 1, 2, 3][key]

B[0]

Resources

Documentation