Python __slots__ AttributeError Fix
In this tutorial, you'll learn about Python slots AttributeError Fix. We cover key concepts, practical examples, and best practices.
Python classes using __slots__ restrict attribute creation to a predefined set. Any attempt to set an attribute not listed in __slots__ raises AttributeError: 'object' has no attribute.
The Wrong Way
class Point:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(10, 20)
p.z = 30
Output:
Traceback (most recent call last):
File "script.py", line 9, in <module>
p.z = 30
AttributeError: 'Point' object has no attribute 'z'
The Right Way
Include all needed attributes in __slots__, or use __dict__ alongside slots:
class Point:
__slots__ = ['x', 'y', 'z']
def __init__(self, x, y, z=0):
self.x = x
self.y = y
self.z = z
p = Point(10, 20)
p.z = 30
print(p.x, p.y, p.z)
Output:
10 20 30
Step-by-Step Fix
1. Add the missing attribute to slots
class Point:
__slots__ = ['x', 'y', 'z'] # Add 'z' to slots
2. Include dict for dynamic attributes
class FlexiblePoint:
__slots__ = ['x', 'y', '__dict__']
def __init__(self, x, y):
self.x = x
self.y = y
p = FlexiblePoint(10, 20)
p.z = 30 # Now works because __dict__ is in slots
print(p.z)
Output:
30
3. Use property descriptors for computed attributes
class Rectangle:
__slots__ = ['width', 'height']
def __init__(self, w, h):
self.width = w
self.height = h
@property
def area(self):
return self.width * self.height
r = Rectangle(10, 5)
print(r.area)
Output:
50
4. Check inheritance with slots
class Base:
__slots__ = ['a']
class Child(Base):
__slots__ = ['b'] # Child has its own slots
obj = Child()
obj.a = 1
obj.b = 2
Prevention Tips
- Plan all attributes before using
__slots__. - Include
__dict__in__slots__if you need dynamic attributes. - Remember that
__slots__are not inherited -- each subclass must define its own. - Use properties for computed values instead of storing them.
- Profile performance gains before adopting
__slots__broadly.
Common Mistakes with slot error
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro