On 2020-02-18 5:43 p.m., Chris Angelico wrote:
On Wed, Feb 19, 2020 at 7:34 AM Soni L. <fakedme...@gmail.com> wrote: > > On 2020-02-18 5:08 p.m., Rhodri James wrote: > > On 18/02/2020 19:43, Soni L. wrote: > >> It'd be nice to have a __valid_getitem_requests__ protocol that, if > >> present, yields pairs such that: > >> > >> for key, value in items(obj): > >> assert obj[key] == value > >> > >> for any obj. > > > > OK, I'll bite. What is this "items()" function you apply to the > > arbitrary object? > > > Similar to len(). Just a shitty wrapper for __valid_getitem_requests__. > > We kinda have a requirement that __iter__ and __contains__ have to be > related, see e.g. dict.__iter__ and dict.__contains__. In an ideal world > dict would yield pairs by default. and dict() would just iterate > whatever. But anyway I digress. As far as my proposal goes, > __valid_getitem_requests__ would provide slightly different semantics > for converting-to-dict: > > dict(items(['a', 'b', 'c'])) == {0: 'a', 1: 'b', 2: 'c'} > dict(items({1: 'a', 2: 'b'})) == {1: 'a', 2: 'b'} > # TODO find other things with __getitem__ and put them here > > In other words: it'd allow creating a dict whose __getitem__ behaviour > is similar to that of the original collection, in the most > straightforward case. (note how the first dict doesn't contain negative > indices or the infinitely many slice objects that can be used to index a > three-element list.) > Is this something you do a lot of? Can you show some real-world (or real-world-cut-down) code that would benefit from this?
Oh yes absolutely. I have a whole library focused on this sort of "canonical keys"-based iteration: https://ganarchy.autistic.space/project/0f74bd87a23b515b45da7e6f5d9cc82380443dab/
(Friendly warning, it does handle sets in a rather unusual way. I've never used that feature outside unit tests, either. Pay no attention to that however, as it's not relevant to this proposal.)
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/2FRJDMBOYU3P3VJWPTKWCFEQ22VUSX4R/ Code of Conduct: http://python.org/psf/codeofconduct/