[Python-Dev] Re: Should the definition of an "(async) iterator" include __iter__?

2021年9月15日 15:49:26 -0700

Guido:
> It's still an iterator, since it duck-types in most cases where an iterator
> is required (notably "for", which is the primary use case for the iteration
> protocols -- it's in the first sentence of PEP 234's abstract).
D'Aprano:
> I don't think it duck-types as an iterator. Here's an example:
>
> class A:
> def __init__(self): self.items = [1, 2, 3]
> def __next__(self):
> try: return self.items.pop()
> except IndexError: raise StopIteration
>
> >>> for item in A(): pass
> ...
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: 'A' object is not iterable
Guido:
> Yes, we all understand that. The reason I invoked "duck typing" is that as
> long as you don't use the iterator in a situation where iter() is called
> on it, it works fine.
I'm confused.
- a "broken" iterator should be usable in `for`;
- `A` is a broken iterator;
but
- `A()` is not usable in `for`.
What am I missing?
--
~Ethan~
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/[email protected]/message/ZMDWM7ICFLD5R7URT2ME4WNYBVQZKNUT/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to