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

Neil Girdhar mistersheik at gmail.com
Thu Apr 21 03:30:27 EDT 2016


Wow, I disagree with this.  The fact that you can override getitem and it
doesn't fix initialization in the constructor to match is definitely
confusing.  The fact that __add__ called on a dict subclass doesn't return
a class of the same type is confusing.  This is why every Python book
advises people not to inherit from builtins.

Let's not get carried away.  This is an optimization for CPython — not a
feature.

On Thu, Apr 21, 2016 at 3:27 AM Michael Selik <mike at selik.org> wrote:

> 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/01129bdd/attachment.html>


More information about the Python-ideas mailing list