On Tue, Feb 18, 2020 at 1:45 PM Soni L. <fakedme...@gmail.com> wrote:

> [...]
> Iteration is done thusly:
>
> def _pairs(obj):
>      if isinstance(obj, collections.abc.Mapping):
>          return iter(obj.items())
>      elif isinstance(obj, collections.abc.Sequence):
>          return iter(enumerate(obj, 0))
>      elif isinstance(obj, collections.abc.Set):
>          return iter(((e, e) for e in obj))
>      else:
>          # maybe there's more stuff I can implement later
>          raise TypeError
>
> I think having a proper protocol for this behaviour would be beneficial,
> as no (monkey)patching would be needed to add support for additional
> collections and data types. The comment saying there may be additional
> data types I've missed would then become irrelevant, as they'd be
> covered by __valid_getitem_requests__.
>
> Sometimes you just want to treat everything as a (read-only) dict.
> Mostly when dealing with user input (e.g. configs), but not only.
>

But what will you do with the pairs?

For mappings and sequences, the pairs represent (key, value) or (index,
value) pairs, which makes sense, since (as you write in your first post)
one can write obj[key] to obtain values from a mapping or sequence (key ~~
index).

But then you go on and propose returning pairs (value, value) for sets, and
there's nothing corresponding to obj[key]. So I'm not sure what your intent
for the proposed is. Why do you want pairs for everything? Suppose obj is a
number x, perhaps you would want to get a single pair (x, x) from the
iteration? (I know that's probably bending the metaphor too far. :-)

Even if you were to answer this question, consider that perhaps your
application is rather unique in this insistence on pairs. Or perhaps you
should've stopped at proposing an API that unifies mappings and sequences
(which more sensible since both support __getitem__) -- isn't that what
your original post was about?

However even for mappings and sequences the analogy only goes so far, since
*iterating* over them behaves very differently: for a mapping, iteration
yields keys, while for a sequence, it yields values. A legitimate question
that comes up from time to time is actually how to *distinguish* between
mappings and sequences -- se the other python-ideas thread that I mentioned
previously.

-- 
--Guido van Rossum (python.org/~guido)
*Pronouns: he/him **(why is my pronoun here?)*
<http://feministing.com/2015/02/03/how-using-they-as-a-singular-pronoun-can-change-the-world/>
_______________________________________________
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/MLWXVXG5JIT34E27XM3UNA3OTYF2XFSG/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to