"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Python Trick: The Magic of __slots__

Python Trick: The Magic of __slots__

Published on 2024-11-02
Browse:538

Python Trick: The Magic of __slots__

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.


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.

Release Statement This article is reproduced at: https://dev.to/devasservice/python-trick-the-magic-of-slots-578j?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3