Coding this day, which of the above is preferred and recommended (both in Python 2 and 3) for subclassing?
I read that UserList
and UserDict
have been introduced because in the past list
and dict
couldn't be subclassed, but since this isn't an issue anymore, is it encouraged to use them?
Depending on your usecase, these days you'd either subclass list
and dict
directly, or you can subclass collections.MutableSequence
and collections. MutableMapping
; these options are there in addition to using the User*
objects.
The User*
objects have been moved to the collections
module in Python 3; but any code that used those in the Python 2 stdlib has been replaced with the collections.abc
abstract base classes. Even in Python 2, UserList
and UserDict
are augmented collections.*
implementations, adding methods list
and dict
provide beyond the basic interface.
The collections
classes make it clearer what must be implemented for your subclass to be a complete implementation, and also let you implement smaller subsets (such as collections.Mapping
, implementing a read-only mapping, or collections.Sequence
for a tuple-like object).
The User*
implementations should be used when you need to implement everything beyond the basic interface too; e.g. if you need to support addition, sorting, reversing and counting just like list
does.
For anything else you are almost always better off using the collections
abstract base classes as a basis; the built-in types are optimised for speed and are not that subclass-friendly. For example, you'll need to override just about every method on list
where normally a new list
is returned, to ensure your subclass is returned instead.
Only if you need to build code that insists on using a list
or dict
object (tested by using isinstance()
is subclassing the types an option to consider. This is why collections.OrderedDict
is a subclass of dict
, for example.
No they are not encouraged anymore. You should not use the UserDict class as it is deprecated. The docs says you can just subclass dict
directly. The userdict
module is gone in Python 3.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With