On Tue, Nov 28, 2017 at 10:49:45AM +1300, Greg Ewing wrote:
> C Anthony Risinger wrote:
> >* Perhaps existence of `__len__` should influence unpacking? There is a 
> >semantic difference (and typically a visual one too) between 1-to-1 
> >matching a fixed-width sequence/container on the RHS to identifiers on 
> >the LHS, even if they look similar (ie. "if RHS has a length make it 
> >fit, otherwise don't").
> 
> -1. There's a convention that an iterator can implement __len__
> to provide a hint about the number of items it will return
> (useful for preallocating space, etc.)

I think you mean __length_hint__ for giving a hint. If an iterator 
supported __len__ itself, I'd expect it to be exact, not a hint. I'm not 
sure that its a strong convention, but we certainly could create custom 
iterators that supported len().

https://www.python.org/dev/peps/pep-0424/


> >While I like the original proposal, adding basic slice support to 
> >iterables is also a nice idea.
> 
> It's not as nice as it seems. You're asking for __getitem__
> to be made part of the iterator protocol, which would be a
> huge change affecting all existing iterators.

There are ways around that. As I said earlier, I'm not going to champion 
this idea, but for the sake of brainstorming, the interpreter could 
implement obj[slice] as:


    if obj has __getitem__:
        call obj.__getitem__(slice)
    elif iter(obj) is obj:
        call itertools.islice(obj, slice)
    else:
        raise TypeError


or similar. Its not literally necessary to require iterators themselves 
to support a __getitem__ method in order to add slicing to the iterator 
protocol.

(Similar to the way bool() falls back on testing for non-zero length in 
the event that __bool__ doesn't exist, or != falls back on calling and 
NOT'ing __eq__ if __ne__ doesn't exist.)

So I think this is solvable if it needs to be solved.



-- 
Steve
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to