I don't think I'd ever guess the intended semantics from the names in a million years. They seem like horribly misnamed methods, made worse by the false suggestion of similarity to list operations.
In 20 years of using Python, moreover, I don't think I've ever wanted the described behavior under any spelling. On Mon, Jun 4, 2018, 6:58 PM George Leslie-Waksman <waks...@gmail.com> wrote: > Semantically, I'm not sure append and extend would be universally > understood to mean don't overwrite. > > This can be accomplished with a custom subclass for your use case: > > ``` > import collections > > > class OverwriteGuardedDict(collections.UserDict): > def append(self, key, value): > if key in self.data: > raise KeyError(key) > self.data[key] = value > > def extend(self, other): > overlap = self.data.keys() & other.keys() > if overlap: > raise KeyError(','.join(overlap)) > self.data.update(other) > ``` > > On Mon, Jun 4, 2018 at 2:24 PM Ben Rudiak-Gould <benrud...@gmail.com> > wrote: > >> I'd like to propose adding `append` and `extend` methods to dicts >> which behave like `__setitem__` and `update` respectively, except that >> they raise an exception (KeyError?) instead of overwriting preexisting >> entries. >> >> Very often I expect that the key I'm adding to a dict isn't already in >> it. If I want to verify that, I have to expand my single-line >> assignment statement to 3-5 lines (depending on whether the dict and >> key are expressions that I now need to assign to local variables). If >> I don't verify it, I may overwrite a dict entry and produce silently >> wrong output. >> >> The names `append` and `extend` make sense now that dicts are defined >> to preserve insertion order: they try to append the new entries, and >> if that can't be done because it would duplicate a key, they raise an >> exception. >> >> In case of error, `extend` should probably leave successfully appended >> entries in the dict, since that's consistent with list.extend and >> dict.update. >> >> The same methods would also be useful on sets. Unfortunately, the >> names make less sense. >> >> -- Ben >> _______________________________________________ >> Python-ideas mailing list >> Python-ideas@python.org >> https://mail.python.org/mailman/listinfo/python-ideas >> Code of Conduct: http://python.org/psf/codeofconduct/ >> > _______________________________________________ > Python-ideas mailing list > Python-ideas@python.org > https://mail.python.org/mailman/listinfo/python-ideas > Code of Conduct: http://python.org/psf/codeofconduct/ >
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/