
On Mon, Dec 19, 2022 at 03:48:01PM -0800, Christopher Barker wrote:
On Mon, Dec 19, 2022 at 3:39 AM Steven D'Aprano <steve@pearwood.info> wrote
In any case, I was making a larger point that this same issue applies to other builtins like float, int and more.
Actually, I think the issue is with immutable types, rather than builtins.
No.
class MyList(list): ... def frobinate(self): ... return "something" ... (MyList(range(5)) + []).frobinate() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'frobinate'
And of course, by default, MyList slices are MyLists too, right? No.
type(MyList(range(5))[1:]) <class 'list'>
This is less of an issue for dicts because there are few dict methods and operators which return dicts. Speaking of dicts, the dict.fromkeys method cooperates with subclasses. That proves that it can be done from a builtin. True, it is a classmethod rather than an instance method, but any instance method can find out its own class by calling `type()` (or the internal, C equivalent) on `self`. Just as we can do from Python.
And that’s just the nature of the beast.
Of course it is not. We can write classes in Python that cooperate with subclasses. The only difference is that builtins are written in C. There is nothing fundamental to C that forces this behaviour. It's a choice. -- Steve