Applying __slots__
in Python Classes
Now that you understand the concept of __slots__
and its benefits, let's explore how to apply it in your Python classes.
Defining __slots__
To use __slots__
in a Python class, you need to define the __slots__
attribute as a list or tuple of strings, where each string represents the name of an allowed attribute.
class Person:
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
In the example above, the Person
class has two allowed attributes: name
and age
.
Accessing Attributes
When you use __slots__
, you can access the attributes of an instance just like you would with a regular class:
person = Person('John Doe', 30)
print(person.name) ## Output: John Doe
print(person.age) ## Output: 30
Limitations and Considerations
As mentioned earlier, there are some limitations to using __slots__
:
- You cannot add dynamic attributes to an instance of a class with
__slots__
.
- You cannot inherit from a class that does not also define
__slots__
.
- You cannot use
__slots__
to define properties or methods.
It's important to carefully consider the trade-offs and limitations of __slots__
before applying it to your classes. In some cases, the memory savings may not be worth the additional constraints.
To illustrate the performance benefits of using __slots__
, let's compare the memory usage of a class with and without __slots__
:
import sys
class PersonWithDict:
def __init__(self, name, age):
self.name = name
self.age = age
class PersonWithSlots:
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
person_with_dict = PersonWithDict('John Doe', 30)
person_with_slots = PersonWithSlots('John Doe', 30)
print(f"Memory usage of PersonWithDict: {sys.getsizeof(person_with_dict)} bytes")
print(f"Memory usage of PersonWithSlots: {sys.getsizeof(person_with_slots)} bytes")
On a Ubuntu 22.04 system, the output of this code might be:
Memory usage of PersonWithDict: 64 bytes
Memory usage of PersonWithSlots: 56 bytes
As you can see, the instance of the PersonWithSlots
class uses less memory than the instance of the PersonWithDict
class, demonstrating the memory optimization benefits of using __slots__
.
By understanding how to apply __slots__
in your Python classes, you can effectively optimize the memory usage of your applications and improve their overall performance.