In this lesson, you will learn how to create custom collection types by inheriting from UserDict and UserList to automatically trigger actions like validation or logging whenever data is modified.
Why not just inherit from dict or list?
When you inherit directly from built-in types like list or dict, some methods (like append or __setitem__) might bypass your custom overrides because they are implemented in C for performance. The collections module provides UserDict and UserList as "wrapper" classes. They are designed specifically for inheritance, ensuring that every modification to your data passes through your custom logic.
Creating a Validated List
Imagine you want a list that strictly forbids negative numbers. By inheriting from UserList, you can "hook" into the assignment process:
from collections import UserList
class PositiveOnlyList(UserList):
def __setitem__(self, index, value):
if value < 0:
raise ValueError("Only positive numbers allowed!")
super().__setitem__(index, value)
def append(self, value):
if value < 0:
raise ValueError("Only positive numbers allowed!")
super().append(value)
my_list = PositiveOnlyList([1, 2, 3])
my_list.append(5) # Works fine
# my_list.append(-1) # Raises ValueError
Creating a Logged Dictionary
Similarly, UserDict allows you to monitor changes to your data. This is perfect for "synchronizing" your state—for example, updating a timestamp or triggering a save file every time a key is updated.
from collections import UserDict
class LoggedDict(UserDict):
def __setitem__(self, key, value):
print(f"Syncing: Setting {key} to {value}")
super().__setitem__(key, value)
data = LoggedDict({'a': 1})
data['b'] = 2 # Prints: Syncing: Setting b to 2
By using these classes, you maintain the full functionality of standard collections while gaining the ability to inject specialized behavior exactly when your data changes. This ensures that your custom data structures remain consistent and predictable throughout your program.
Key Takeaway: Use UserDict and UserList as base classes when you need to intercept and customize how data is added, changed, or removed in your collections.