[Python-ideas] Override dict.__new__ to raise if cls is not dict; do the same for str, list, etc.

Michael Selik mike at selik.org
Thu Apr 21 03:27:35 EDT 2016

On Thu, Apr 21, 2016 at 1:58 AM Neil Girdhar <mistersheik at gmail.com> wrote:

> The pros are that unsuspecting users won't fall into the trap associated
> with inheriting from dict, list or set. ...  It's people who don't know the
> problems and have no way of finding out until they spend a day debugging
> why overriding some method on a derived class of a derived class that
> ultimately inherits from dict doesn't work.

I feel your pain. However, what you see as a failure or defect of the
builtins is actually a feature! :-)

The downstream programmer should not be expected to know the implementation
details of a dict. You don't want to read the source, you just want to use
the public interface. You should be able to subclass and override methods
as you like without worrying about hidden internal relationships. You
should be able to override ``__getitem__`` without accidentally affecting
things like ``values``.

I guess it's a case of "a little knowledge is dangerous". Someone who knows
nothing about dict implementation would not expect to see a change in
method A because of an override of method B. The expert is keeping the
novice safe. It's the journeyman who suffers.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160421/8f7b1cbe/attachment.html>

More information about the Python-ideas mailing list