Steven D'Aprano wrote:
> On Fri, Dec 27, 2019 at 02:22:48AM -0000, Marco Sulla via Python-ideas wrote:
> > It's very common to see:
> > for i, x in enumerate(sequence):
> >     [...]
> > 
> > Yes, that is very common, except that "sequence" can be any iterable 
> with an unpredictable length, or even an infinite length, such as a 
> generator

There's no problem. Also iterators and generators can have a entries() method 
that returns a view, or a generator.

> that will cause a lot of code duplication. Just in the 
> built-ins, we would have to add those two methods to:
> 
> dicts
> dict views (keys, values and items)
> sets
> frozensets
> lists
> tuples
> strings
> bytes
> bytearrays
> 
> (did I miss any?)

Yes and no: you added too much! dict views, set and frozenset are not 
sequences, and furthermore does not require such methods. You missed 
memoryview. About maps, well... wait and read ^^

And even if they are not sequences, I think also file-like objects can benefit 
from an entries() method:

```
with open(somepath) as f:
    for i, line in f.entries():
        [...]
```


>. Even if the methods can share an implementation 
> (probably calling enumerate and range behind the scenes)

This can be a fast and furious implementation for a first draft, but IMHO they 
should return a view, like for maps. 

> for i, x in enumerate(items):  # works with every iterable
> for i, x in items.entries():   # only works with some sequences

Well, enumerate does work with **almost** every iterable. It does not work with 
maps, you have to use keys(). You can say <<you can still use enumerate with a 
map>>, but for another purpose.

Currently, if you want to iterate over a map items or over a sequence, 
iterable, generator and file entries, you already have to use two different 
APIs.

Maybe we can simply add an alias for keys() and entries() for maps, so we have 
really them for all iterables.

Furthermore, there's also an unexpected bonus for enumerate: enumerate could 
try to return entries() for not maps as first action. I don't know if enumerate 
is written in py or in c, but if it's written in py, this will be boost 
enumerate.

IMHO, indexes() could be simply added to all sequences without problems. 
entries(), since it can be applied to not sequences too, IMHO requires another 
CPython type: Enumerable. Who inherits also Enumerable must implement an 
entries() method. This could be also an ABC class.
_______________________________________________
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/6JVZP2RF5AYYTK6PJFB6CKII3XH3PZ3P/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to