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

Steven D'Aprano steve at pearwood.info
Thu Apr 21 07:30:37 EDT 2016

On Thu, Apr 21, 2016 at 04:36:54PM +1000, Nick Coghlan wrote:

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

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):

and now MyInt() + MyInt() will return a MyInt, rather than a regular 

Getting the list of dunder methods is easy, but telling whether or not 
they should return an instance of the subclass may not be.



More information about the Python-ideas mailing list