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.)
(perhaps a better name for this property is needed? how about "canonical
keys"? as in, __valid_getitem_requests__ should contain only the
canonical "keys" (the python datamodel specifically says __getitem__
takes a self and a key[1]) of a collection, and their respective values.)
[1] https://docs.python.org/3/reference/datamodel.html#object.__getitem__
_______________________________________________
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/CEHZRUGM63P7WF3RTOUPLM2GIR3FDLZS/
Code of Conduct: http://python.org/psf/codeofconduct/