On Wed, Feb 19, 2020 at 7:58 AM Soni L.
On 2020-02-18 5:43 p.m., Chris Angelico wrote:
On Wed, Feb 19, 2020 at 7:34 AM Soni L.
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/0f74bd87a23b515b45da7e6f5d9cc8238044...
(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.)
Too short, didn't read. Specifically, I'm not going to go digging through your links to find code to justify why you want this feature. Post some code here, or at very least, link directly to the code that would be improved by this feature. Soni, you're very close to my mental blocklist. Please put a bit more effort into your posts to make it clear what you're actually proposing, rather than making each of us do the work. ChrisA