5.12 UserDict -- Class wrapper for dictionary objects

The module defines a mixin, DictMixin, defining all dictionary methods for classes that already have a minimum mapping interface. This greatly simplifies writing classes that need to be substitutable for dictionaries (such as the shelve module).

This module also defines a class, UserDict, that acts as a wrapper around dictionary objects. 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.

The UserDict module defines the UserDict class and DictMixin:

class UserDict( [initialdata])
Class that simulates a dictionary. The instance's contents are kept in a regular dictionary, which is accessible via the data attribute of UserDict instances. If initialdata is provided, data is initialized with its contents; note that a reference to initialdata will not be kept, allowing it be used for other purposes. Note: For backward compatibility, instances of UserDict are not iterable.

class IterableUserDict( [initialdata])
Subclass of UserDict that supports direct iteration (e.g. for key in myDict).

In addition to supporting the methods and operations of mappings (see section 3.8), UserDict and IterableUserDict instances provide the following attribute:

data
A real dictionary used to store the contents of the UserDict class.

class DictMixin( )
Mixin defining all dictionary methods for classes that already have a minimum dictionary interface including __getitem__(), __setitem__(), __delitem__(), and keys().

This mixin should be used as a superclass. Adding each of the above methods adds progressively more functionality. For instance, defining all but __delitem__ will preclude only pop and popitem from the full interface.

In addition to the four base methods, progressively more efficiency comes with defining __contains__(), __iter__(), and iteritems().

Since the mixin has no knowledge of the subclass constructor, it does not define __init__() or copy().

See About this document... for information on suggesting changes.