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

Terry Reedy tjreedy at udel.edu
Thu Apr 21 19:13:04 EDT 2016

On 4/21/2016 7:30 AM, Steven D'Aprano wrote:

> I wonder whether we should have a class decorator which automatically
> adds the appropriate methods?
> It would need some sort of introspection to look at the superclass and
> adds overridden methods? E.g. if the superclass is float, it would add a
> bunch of methods like:
> def __add__(self, other):
>     x = super().__add__(other)
>     if x is NotImplemented:
>         return x
>     return type(self)(x)
> but only if they aren't already overridden. Then you could do this:
> @decorator  # I have no idea what to call it.
> class MyInt(int):
>     pass
> and now MyInt() + MyInt() will return a MyInt, rather than a regular
> int.
> Getting the list of dunder methods is easy, but telling whether or not
> they should return an instance of the subclass may not be.
> Thoughts?

Interesting idea.  I would start with a TDDed fix_int_subclass, then a 
TDDed fix_list_subclass, and only then think about whether there is 
enough common code to refactor.

Terry Jan Reedy

More information about the Python-ideas mailing list