Python’s flexibility with dynamic attributes is one of its strengths, but sometimes you want to optimize memory usage and performance.
Enter __slots__
, a feature that allows you to define a fixed set of attributes for your class, reducing memory overhead and potentially speeding up attribute access.
How It Works
Normally, Python objects are implemented as dictionaries for storing attributes, which can lead to higher memory consumption.
By defining __slots__
in your class, you instruct Python to use a more memory-efficient internal structure.
This is especially useful when you know the attributes a class will have ahead of time and want to avoid the overhead of a full dictionary.
Here’s a demonstration of how to use __slots__
:
class Point:
__slots__ = ['x', 'y'] # Define the allowed attributes
def __init__(self, x, y):
self.x = x
self.y = y
# Create a Point instance
p = Point(10, 20)
print(p.x) # Output: 10
print(p.y) # Output: 20
# Attempting to add a new attribute will raise an AttributeError
try:
p.z = 30
except AttributeError as e:
print(e) # Output: 'Point' object has no attribute 'z'
# Output:
# 10
# 20
# 'Point' object has no attribute 'z'
In this example, __slots__
restricts the Point
class to only the x
and y
attributes.
Attempting to set any attribute not listed in __slots__
results in an AttributeError
.
Get the eBook
Inside, you'll discover a plethora of Python secrets that will guide you through a journey of learning how to write cleaner, faster, and more Pythonic code. Whether it's mastering data structures, understanding the nuances of object-oriented programming, or uncovering Python's hidden features, this ebook has something for everyone.
Why It’s Cool
Using __slots__
can lead to significant memory savings, especially when creating large numbers of instances, by eliminating the overhead of the attribute dictionary.
It can also improve attribute access speed.
However, be cautious: __slots__
can limit some dynamic capabilities of Python objects and may not be suitable for all use cases.
If you are not a Premium Django Series Subscriber, sign up below and get a 25% discount on the yearly membership:
Feel free to use the feedback buttons or send in a comment for future content you would love to see or what new things you learned from this post.
Also, share it with a friend who would love to read it.