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

Nick Coghlan ncoghlan at gmail.com
Thu Apr 21 02:36:54 EDT 2016


On 21 April 2016 at 12:51, Neil Girdhar <mistersheik at gmail.com> wrote:

> Sometimes users inherit from builtin types only to find that their
> overridden methods are not called.  Instead of this being a trap for
> unsuspecting users, I suggest overriding the __new__ method of these types
> so that it will raise with an informative exception explaining that, e.g.,
> instead of inheriting from dict, you should inherit from UserDict.
>
> I suggest this modification to any Python implementation that has special
> versions of classes that cannot easily be extended, such as CPython.  If
> another Python implementation allows dict (e.g.) to be extended easily,
> then it doesn't have to raise.
>

Builtins can be extended, you just have to override all the methods where
you want to change the return type:

>>> from collections import defaultdict, Counter, OrderedDict
>>> issubclass(defaultdict, dict)
True
>>> issubclass(Counter, dict)
True
>>> issubclass(OrderedDict, dict)
True

This isn't hard as such, it's just tedious, so it's often simpler to use
the more subclass friendly variants that dynamically look up the type to
return and hence let you get away with overriding a smaller subset of the
methods.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160421/056ba1d1/attachment.html>


More information about the Python-ideas mailing list