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 ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.