generator/coroutine terminology
Marko Rauhamaa
marko at pacujo.net
Mon Mar 16 03:40:15 EDT 2015
Chris Angelico <rosuav at gmail.com>:
> On Mon, Mar 16, 2015 at 6:12 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
>>
>> I was actually referring to the offered API. It still seems to me like
>> all iterators could offer close(), send() and throw(). Why? To make all
>> iterators drop-in replacements of each other.
>
> [...]
>
> That just adds unnecessary overhead to every iterator.
Trivial implementations are a normal way to satisfy an API. That's why
/dev/null implements a close() method, for example.
> Also, what happens when you throw something into iter([1,2,3]) ? Or
> send it a value? What happens?
I would expect iter([1, 2, 3]) to behave highly analogously to
(x for x in [1, 2, 3]).
===begin /tmp/test.py===================================================
#!/usr/bin/env python3
def main():
it = (x for x in [1, 2, 3])
print(next(it))
while True:
try:
print(it.send("hello"))
except StopIteration:
break
if __name__ == "__main__":
main()
===end /tmp/test.py=====================================================
========================================================================
$ python3 /tmp/test.py
1
2
3
========================================================================
but:
===begin /tmp/test.py===================================================
#!/usr/bin/env python3
def main():
it = iter([1, 2, 3])
print(next(it))
while True:
try:
print(it.send("hello"))
except StopIteration:
break
if __name__ == "__main__":
main()
===end /tmp/test.py=====================================================
========================================================================
$ python3 /tmp/test.py
1
Traceback (most recent call last):
File "/tmp/test.py", line 13, in <module>
main()
File "/tmp/test.py", line 8, in main
print(it.send("hello"))
AttributeError: 'list_iterator' object has no attribute 'send'
========================================================================
Marko
More information about the Python-list
mailing list