This rule raises an issue when code assigns a value to an attribute that is not listed in the class’s __slots__ declaration.
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:
__dict__ for each instance__slots__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'
When code attempts to assign to an attribute not in __slots__, the application will crash with an AttributeError at
runtime. This can lead to:
If the attribute should be part of the class’s interface, add it to the __slots__ declaration.
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__
class User:
__slots__ = ['name', 'email', 'age']
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age