[Python-ideas] Dict joining using + and +=
storchaka at gmail.com
Mon Mar 4 08:43:48 EST 2019
01.03.19 12:44, Steven D'Aprano пише:
> On Fri, Mar 01, 2019 at 08:47:36AM +0200, Serhiy Storchaka wrote:
>> Currently Counter += dict works and Counter + dict is an error. With
>> this change Counter + dict will return a value, but it will be different
>> from the result of the += operator.
> That's how list.__iadd__ works too: ListSubclass + list will return a
> value, but it might not be the same as += since that operates in place
> and uses a different dunder method.
> Why is it a problem for dicts but not a problem for lists?
Because the plus operator for lists predated any list subclasses.
>> Also, if the custom dict subclass implemented the plus operator with
>> different semantic which supports the addition with a dict, this change
>> will break it, because dict + CustomDict will call dict.__add__ instead
>> of CustomDict.__radd__.
> That's not how operators work in Python or at least that's not how they
> worked the last time I looked: if the behaviour has changed without
> discussion, that's a breaking change that should be reverted.
You are right.
> What's wrong with doing this?
> new = type(self)()
> Or the equivalent from C code. If that doesn't work, surely that's the
> fault of the subclass, the subclass is broken, and it will raise an
Try to do this with defaultdict.
Note that none of builtin sequences or sets do this. For good reasons
they always return an instance of the base type.
More information about the Python-ideas