[Python-ideas] Override dict.__new__ to raise if cls is not dict; do the same for str, list, etc.
mistersheik at gmail.com
Thu Apr 21 03:20:40 EDT 2016
Good point, I withdraw my suggestion. I think it's unfortunate for Python
to have traps like this, but I don't see a nice way to protect users while
still letting people do whatever they want.
On Thu, Apr 21, 2016 at 3:03 AM Neil Girdhar <mistersheik at gmail.com> wrote:
> I guess that's fair.
> On Thu, Apr 21, 2016 at 2:36 AM Nick Coghlan <ncoghlan at gmail.com> wrote:
>> 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)
>> >>> issubclass(Counter, dict)
>> >>> issubclass(OrderedDict, dict)
>> 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
>> Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas