What’s the difference between UserDict, dict and ABC and which one is recommended? The docs seem to deprecate UserDict?
Also it seems UserDict’s update() would use my setitem method whereas dict doesn’t? Which methods are really essential to override given I want custom setitem and getitem function?
With ABCs I’d have to implement absolutely all methods since it provides no default implementation?
I want to make a dict that does two things:
intern()all keys and values- store some of the values in an SQLite database
So which of UserDict, dict and ABC would best allow me to do this?
If you want a custom collection that actually holds the data, subclass dict. This is especially useful if you want to extend the interface (e.g., add methods).
None of the built-in methods will call your custom
__getitem__/__setitem__, though. If you need total control over these, create a custom class that implements thecollections.MutableMappingabstract base class instead.The ABC does not provide a means to store the actual data, only an interface with default implementations for some methods. These default implementations will, however, call your custom
__getitem__and__setitem__. You will have to use an internaldictto hold the data, and implement all abstract methods:__len__,__iter__,__getitem__,__setitem__, and__delitem__.The class
UserDictfrom thecollectionsmodule (in Python 2, the module is calledUserDictas well) is a wrapper around an internaldict, implementing theMutableMappingABC. If you want to customize the behavior of adict, this implementation could be a starting point.In summary:
dict. It’s totally up to you if and how you store the data.MutableMappingusing an internal “real”dictas storage. If you want a dict-like storage collection but override some methods exposed bydict, this might be a good starting point for you. But make sure to read the code to know how the basic methods are implemented, so that you are consistent when overriding a method.