Customize container behavior by subclassing wrapper types.
What You Will Learn
UserDict, UserList, and UserString wrap a dictionary, list, or string with a data attribute. They are often easier to override than low-level built-in types because methods are designed to cooperate with subclasses.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from collections import UserDict, UserList, UserString
class UppercaseKeys(UserDict):
def __setitem__(self, key, value):
super().__setitem__(str(key).upper(), value)
settings = UppercaseKeys()
settings['mode'] = 'on'
print(settings.data)
print(UserList([1, 2]).data)
print(UserString('note').data)
How the Example Works
- The imports provide the standard-library tools used in the demonstration: collections.
- The class UppercaseKeys groups data and behavior; its methods run when called on an instance.
- The variable settings holds the result of UppercaseKeys(). Later lines use that value or inspect how it changes.
- The variable settings['mode'] holds the result of 'on'. Later lines use that value or inspect how it changes.
Expected output from the example:
{'MODE': 'on'}
[1, 2]
note
When You Would Use This
Decide which input types are valid, what output should be produced, and which cases should fail clearly. A small self-contained demonstration is a good starting point before adding file access, network calls, or application state.
Practice: Modify the Code
Implement a validating UserList that accepts only positive integers.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming custom __setitem__ behavior also changes lookup without implementing __getitem__.
- Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.
Key Takeaways
- Customize container behavior by subclassing wrapper types.
- UserDict, UserList, and UserString wrap a dictionary, list, or string with a data attribute.
- Apply this operation only after checking the assumptions and input conditions shown in the example.