
On Tue, 20 Dec 2022 at 20:20, Steven D'Aprano <steve@pearwood.info> wrote:
On Mon, Dec 19, 2022 at 05:53:38PM -0800, Ethan Furman wrote:
Personally, every other time I've wanted to subclass a built-in data type, I've wanted the built-in methods to return my subclass, not the original class.
Enums are special. But outside of enums, I cannot think of any useful situation where the desirable behaviour is for methods on a subclass to generally return a superclass rather than the type of self.
Its normal behaviour for operations on a class K to return K instances, not some superclass of K. I dare say there are a few, but they don't come to mind.
How should it do that, if the constructor for K has a different signature from the constructor for K's superclass that is providing the method? How is the superclass to know how to return a K? Should the vanilla dict.__or__ method be able to take two defaultdicts and return a defaultdict, or is it reasonable to demand that, in this situation, defaultdict needs to define the method itself?
defaultdict(list) | defaultdict(list) defaultdict(<class 'list'>, {}) defaultdict.__or__ <slot wrapper '__or__' of 'collections.defaultdict' objects>
I'm not sure how dict.__or__ would be expected to cope with this situation. Yes, I'm sure it would be convenient. It would also have some extremely annoying consequences. ChrisA