Robinson
Robinson

Reputation: 31

Is there any difference between UserDict and Dict?

If I want a class to have a dictionary behavior, why should I inherit from dict or UserDict?

Upvotes: 3

Views: 900

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881863

You can inherit from dict in any Python that's version 2.2 or better, but you'll have to override every single method of interest -- for example, your override of __getitem__ will not be used by get unless you also override that one, and so on, and so forth.

The UserDict.DictMixin mix-in goes back a lot further and lets you implement just a few methods: the other methods, as supplied by the mix-in, will pick up and use your own overrides. Note, however, from the docs:

Starting with Python version 2.6, it is recommended to use collections.MutableMapping instead of DictMixin.

The new ABCs (Abstract Base Classes) in the collections module have much the same advantages as good old UserDict.DictMixin, wider applicability, and more regularity.

Upvotes: 8

Related Questions