On Tue, Jun 05, 2018 at 09:44:59AM -0700, Chris Barker via Python-ideas wrote:
> I think your proposal got a bit confused by the choice of names, and that > you were proposing two things, one of which I think already exists > (setdefault). Ben's very first paragraph in this thread says: 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. setdefault does not raise an exception. So while your enthusiasm does you credit (setdefault is an excellent little method that is not known anywhere near as well as it ought to be) I don't think it is the least bit relevant here. Ben's proposal is for something like your exclusive_add below (although written in C so it would be atomic), and then given that, something like: def exclusive_update(self, other): # simplified version for key in other: self.exclusive_add(key, other[key]) except that it isn't clear to me what should happen if a key matches: 1) should the update have an "all or nothing" guarantee? (either the entire update succeeds, or none of it) 2) if not, what happens on partial success? are the results dependent on the order of the attempted update? > So, I _think_ what you are proposing is that there be a method something > like: > > def exclusive_add(self, key, value): > if key in self: > raise KeyError("the key: {} already exists in this > dict".format(key)) > self[key] = value > > Which would make sense if that is a common use case, and you make a pretty > good case for that, with the analogy to UNIQUE in database tables. I'm not sure that it is so common. I think I've wanted the opposite behaviour more often: aside from initialisation, only allow setting existing keys, and raise if the key doesn't exist. Nor do I think the DB analogy is very convincing, since we have no transactions with ACID guarantees for dicts. Pretty much the only similarity between a dict and a DB is that they both map a key to a value. > I will point out that the DB case is quite different, because python dicts > have a way to of spelling it that's really pretty straightforward, > performant and robust. I'm confused... first you say that Ben makes a good case for this functionality with the DB analogy, and then one sentence later, you say the DB case is very different. So not a good case? I don't understand. And what is this way of spelling "it" (what is it?) that's straightforward and robust? You've completely lost me, sorry. -- Steve _______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/