[Python-Dev] The type of the result of the copy() method

Raymond Hettinger raymond.hettinger at gmail.com
Sun Oct 29 13:41:25 EDT 2017

> On Oct 29, 2017, at 10:04 AM, Guido van Rossum <guido at python.org> wrote:
> Without an answer to these questions I think it's better to admit defeat and return a dict instance 

I think it is better to admit success and recognize that these APIs have fared well in the wild.

Focusing just on OrderedDict() and dict(),  I don't see how to change the copy() method for either of them without breaking existing code.  OrderedDict *is* a dict subclass but really does need to have copy() return an OrderedDict.

The *default* behavior for any pure python class is for copy.copy() to return an instance of that class.  We really don't want ChainMap() to return a dict instance -- that would defeat the whole purpose of having a ChainMap in the first place.

And unlike the original builtin classes, most of the collection classes were specifically designed to be easily subclassable (not making the subclasser do work unnecessarily).  These aren't accidental behaviors:

    class ChainMap(MutableMapping):

        def copy(self):
            'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
            return self.__class__(self.maps[0].copy(), *self.maps[1:])

Do you really want that changed to:

            return ChainMap(self.maps[0].copy(), *self.maps[1:])

Or to:

            return dict(self)

Do you really want Serhiy to sweep through the code and change all of these long standing APIs, overriding the decisions of the people who designed those classes, and breaking all user code that reasonably relied on those useful and intentional behaviors?


P.S.  Possibly related:  We've gone out of way in many classes to have a __repr__ that uses the name of the subclass.  Presumably, this is to make life easier for subclassers (one less method they have to override), but it does make an assumption about what the subclass signature looks like.  IIRC, our position on that has been that a subclasser who changes the signature would then need to override the __repr__.   ISTM that similar reasoning would apply to copy.

More information about the Python-Dev mailing list