This rule raises an issue when code assigns a value to an attribute that is not listed in the class’s __slots__ declaration.

Why is this an issue?

In Python, the __slots__ class attribute is used to explicitly declare which instance attributes a class can have. When a class defines __slots__, Python restricts instances to only those attributes, preventing the creation of new attributes dynamically.

This restriction serves several purposes:

Assigning to an attribute that is not in __slots__ causes Python to raise an AttributeError at runtime:

class Point:
    __slots__ = ['x', 'y']

p = Point()
p.x = 10  # OK
p.z = 20  # Raises AttributeError: 'Point' object has no attribute 'z'

What is the potential impact?

When code attempts to assign to an attribute not in __slots__, the application will crash with an AttributeError at runtime. This can lead to:

How to fix it

If the attribute should be part of the class’s interface, add it to the __slots__ declaration.

Code examples

Noncompliant code example

class User:
    __slots__ = ['name', 'email']

    def __init__(self, name, email, age):
        self.name = name
        self.email = email
        self.age = age  # Noncompliant: "age" is not in __slots__

Compliant solution

class User:
    __slots__ = ['name', 'email', 'age']

    def __init__(self, name, email, age):
        self.name = name
        self.email = email
        self.age = age

Resources

Documentation