29.10.17 19:04, Guido van Rossum пише:
It's somewhat problematic. If I subclass dict with a different constructor, but I don't overload copy(), how can the dict.copy() method construct a correct instance of the subclass? Even if the constructor signatures match, how can dict.copy() make sure it copies all attributes properly? Without an answer to these questions I think it's better to admit defeat and return a dict instance -- classes that want to do better should overload copy().

I notice that Counter.copy() has all the problems I indicate here -- it works as long as you don't add attributes or change the constructor signature. I bet this isn't documented anywhere.

I am familiar with these reasons, and agree with them. But I'm curious why some collections chose the way of creating an instance of the same class. For creating an instance of the same class we have the __copy__() method.

An attempt to preserve a class in the returned value can cause problems. For example, the __add__() and __mul__() methods of deque first make a copy of the same type, and this can cause a crash [1]. Of course this is not occurred in real code, it is just yet one way of crashing the interpreter from Python code. list and tuple are free from this problem since their corresponding methods (as well as copy()) create an instance of the corresponding base type.

I think there were reasons for copying the type in results. It would be nice to formalize the criteria, in what cases copy() and other methods should return an instance of the base class, and in what cases they should create an instance of the same type as the original object. This would help for new types. And maybe we need to change some existing type (the inconsistency between WeakKeyDictionary and WeakSet looks weird).

[1] https://bugs.python.org/issue31608

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to