List vs UserList and dict vs UserDict

Coding on that day, which of the above is preferred and recommended (both in Python 2 and 3) for the subclass?

I read that UserList and UserDict were introduced because in the past list and dict could not be subclasses, but since this is no longer a problem, is it recommended to use them?

+6
source share
2 answers

Depending on your user database these days you will either be subclasses of list and dict directly, or you can subclass collections.MutableSequence and collections. MutableMapping collections. MutableMapping ; these options exist in addition to using User* objects.

User* objects have been moved to the collections module in Python 3; but any code used in stdlib Python 2 has been replaced by the base collections.abc classes. Even in Python 2, UserList and UserDict are complementary implementations of collections.* , The addition of the list and dict methods provides in addition to the main interface.

The collections classes specify what should be implemented for your subclass as a full implementation, and also allows you to implement smaller subsets (e.g. collections.Mapping , implement read-only matching, or collections.Sequence for an object that looks like a tuple).

User* implementations should be used when you need to implement everything except the base interface; for example, if you need to support adding, sorting, reversing, and counting, like list does.

Otherwise, you are almost always better off using the base collections classes as the basis; built-in types are optimized for speed and not suitable for subclassing. For example, you need to override almost every method on list , where a new list usually returned to ensure that your subclass will be returned.

Only if you need to create code that insists on using a list or dict object (tested with isinstance() ) will subclass the types you need to consider. This is why collections.OrderedDict is a subclass of dict , for example.

+10
source

No , they are no longer encouraged. You should not use the UserDict class as it is deprecated . The docs say you can just subclass the dict directly. userdict module removed in Python 3.0

+4
source

Source: https://habr.com/ru/post/974250/


All Articles