← Back to context

Comment by ok123456

7 days ago

If you're inheriting from dict to extend its behavior, there are a lot of side effects with that, and it's recommended to use https://docs.python.org/3/library/collections.html#collectio... instead.

From right above where you linked to:

> The need for this class has been partially supplanted by the ability to subclass directly from dict; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute.

Sounds like (unless you need the dict as a separate data member) this class is a historical artefact. Unless there's some other issue you know of not mentioned in the documentation?

  • dict doesn't follow the usual object protocol, and overloaded methods are runtime dependent. It's only guaranteed that non-overloaded methods are resolved least surprisingly.

    • I think you mean overridden (i.e. defined in both base class and derived class) rather than overloaded (i.e. defined more than once in a single place but with different argument types, as least from a typing point of view [1]). Your comment seriously confused me till I figured that out.

      [1] https://typing.python.org/en/latest/spec/overload.html

      Even then, to be honest I'm a bit sceptical. Can you point at a link in the official documentation that says overriding methods of dictionaries may not work? I would have thought the link to UserDict would have mentioned that if true. What do you mean they are "runtime dependent"?

      2 replies →

No, that is not the recommendation. People routinely and reliably inherit from dict.

The UserDict class is mostly defunct and is only still in the standard library because there were a few existing uses that were hard to replace (such as avoiding base class conflicts in multiple inheritance).

  • Ah, Python. The language where nobody agrees on the right way to do things, ans just does their own instead. Five ways to describe an object of a certain shape? Six package managers, with incompatible but overlapping ways to publish packages, but half of them without a simple way to update dependencies? Asynchronous versions of everything? Metaprogramming that makes Ruby blush? Yes! All of it! Lovely.

  • UserDict is not formally deprecated but it will be someday, so code that relies on it is not future-proof.