[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
Wed Apr 20 22:55:39 EDT 2016


Specifically, I'm suggesting something like

class dict:
    def __new__(cls):
          if cls is not dict:
                 raise RuntimeError("Cannot inherit from dict; inherit from 
UserDict instead")
          super().__new__(cls)

On Wednesday, April 20, 2016 at 10:51:37 PM UTC-4, Neil Girdhar 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.
>
> Best,
>
> Neil
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160420/e7e66f03/attachment.html>


More information about the Python-ideas mailing list