[Python-ideas] Dict joining using + and +=

Steven D'Aprano steve at pearwood.info
Mon Mar 4 11:50:12 EST 2019


On Mon, Mar 04, 2019 at 03:43:48PM +0200, Serhiy Storchaka wrote:
> 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.

That doesn't answer my question. Just because it is older is no 
explaination for why this behaviour is not a problem for lists, or a 
problem for dicts.

[...]
> >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
> >exception.
> 
> Try to do this with defaultdict.

I did. It seems to work fine with my testing:

py> defaultdict()
defaultdict(None, {})

is precisely the behaviour I would expect.

If it isn't the right thing to do, then defaultdict can override __add__ 
and __radd__.


> Note that none of builtin sequences or sets do this. For good reasons 
> they always return an instance of the base type.

What are those good reasons?


-- 
Steven


More information about the Python-ideas mailing list