An "adapter", superset of an iterator

Chris Angelico rosuav at gmail.com
Wed May 3 17:29:14 EDT 2023


On Thu, 4 May 2023 at 02:25, fedor tryfanau <fedor.tryfanau at gmail.com> wrote:
>
> I've been using python as a tool to solve competitive programming problems
> for a while now and I've noticed a feature, python would benefit from
> having.
> Consider "reversed(enumerate(a))". This is a perfectly readable code,
> except it's wrong in the current version of python. That's because
> enumerate returns an iterator, but reversed can take only a sequence type.
>
> The feature I am describing (and proposing) solves this.
> Introducing an adapter type: this is an iterator, but it's items can be
> accessed out of order.
> More formally it has to:
> 1. Have __getitem__ to allow access by index
> 2. Have __len__
> 3. Be immutable
> (It is a lot like the sequence protocol)
>
> An adapter can be converted to an iterator by accessing it from 0 to
> len(adapter). Which is done by iter(). (or by __iter__, I don't know which
> implementation would be "right")
> ```
> iter(a)
> #is equivalent to
> (a[i] for i in range(len(a)))
> ```
> For example any tuple is a valid adapter and any list can be easily
> converted to one.
>
> Built-in adapter-generators:
> "map" function should really return an adapter.

The trouble with that is that map() already accepts any iterator. So
you're asking for map to be able to return an iterator if given an
iterator, or an adapter if given an adapter. That makes it quite
complicated to use and reason about.

In general, it's probably safest to just coalesce things to list when
you need to:

reversed(list(enumerate(a)))

because otherwise there are many MANY questions left open. For
example, in what order are the elements of a retrieved? with
reversed(enumerate(a)) it's not clear, but if you force to list first,
it is (and you know exactly when they're accessed too).

ChrisA


More information about the Python-list mailing list