Previous Page
Next Page

8.9. The UserDict Module

The main content of the UserDict module of Python's standard library (analogous to those of now semi-obsolete modules UserList and UserString) used to be classes that emulated the behavior of standard built-in container types. Their usefulness used to be that, in the legacy object model, you could not inherit from built-in types, and what we now call the legacy object model used to be the only object model available in Python. Nowadays, you can simply subclass built-in types such as list and dict, so there isn't much point in emulating the built-in types by Python-coded classes. However, the UserDict module does contain one class that is still extremely useful.

Implementing the full interface defined as a "mapping" (i.e., the interface of a dictionary) takes a lot of programming because dictionaries have so many useful and convenient methods. The UserDict module supplies one class, DictMixin, that makes it easy for you to code classes that offer the complete mapping interface while coding a minimal number of methods: your class just needs to inherit (possibly multiply inherit) from UserDict.DictMixin. At a minimum, your class must define methods _ _getitem_ _, keys, and copy; if instances of your class are meant to be mutable, then your class must also define methods _ _setitem_ _ and _ _delitem_ _.

Optionally, for efficiency, you may also choose to define methods _ _contains_ _, _ _iter_ _, and/or iteritems; if you don't define such methods, your DictMixin superclass defines them on your behalf, but the versions you get by inheritance from DictMixin are probably substantially less efficient than ones you could define yourself on the basis of your knowledge of your class's specific concrete structure (the many other methods of the mapping interface, on the other hand, tend to get reasonably efficient implementations even just by inheritance from DictMixin, so there is generally no particular need to define them in your own class).


Previous Page
Next Page