views:

179

answers:

3

Hi all,

I'm currently reading Dive Into Python by Mark Pilgrim, and have gotten to the section on inheritance. In section 5.5, Pilgrim mentions the differences between inheriting from the wrapper class UserDict vs inheriting from the built-in dict type.

I'm having trouble understanding why anyone would even bother with the wrapper class... What are the benefits of inheriting from the UserDict wrapper class (or any of the other UserXxx classes)?

Your input is much appreciated. Thanks!

+3  A: 

You're right:

The need for this class has been largely supplanted by the ability to subclass directly from dict (a feature that became available starting with Python version 2.2). Prior to the introduction of dict, the UserDict class was used to create dictionary-like sub-classes that obtained new behaviors by overriding existing methods or adding new ones.

Note the first sentence. This comes from the documentation of UserDict.

Oh, and in Python 3 it's gone.

Eli Bendersky
+2  A: 

The wrapper classes have been removed from Python 3, as they haven't been all that useful for a while now. The mixin class, UserDict.DictMixin, is a completely different story -- its useful features are now found all over the "abstract base classes" in the collections module (Python 2.6 and 3.*).

Alex Martelli
+1  A: 

I found, on the page you linked to, a hint as to the answer:

In versions of Python prior to 2.2, you could not directly subclass built-in datatypes like strings, lists, and dictionaries. To compensate for this, Python comes with wrapper classes that mimic the behavior of these built-in datatypes: UserString, UserList, and UserDict. Using a combination of normal and special methods, the UserDict class does an excellent imitation of a dictionary. In Python 2.2 and later, you can inherit classes directly from built-in datatypes like dict.

In reality, today you probably want to sub-class dict, rather than UserDict.

Matthew Schinckel