bslatkin / effectivepython

Effective Python: Second Edition — Source Code and Errata for the Book
https://effectivepython.com
2.24k stars 718 forks source link

Document how to chain iterator send() for Python 2 #50

Closed bslatkin closed 5 years ago

bslatkin commented 6 years ago

Since there's no yield from you need to use a loop in order to chain iterators. However, in the default explained by item 40, a simple loop doesn't properly pass through sending. You have to nest the send() calls like this:

    it = count_neighbors(y, x)
    try:
        value = next(it)
        while True:
            value = it.send((yield value))
    except MyReturn as e:
        neighbors = e.value

A full example showing the problem is worked out in this gist:

https://gist.github.com/bslatkin/6934d53441198f3db30d32cb7f1dbf73#file-my_coroutine_in_py_27-py-L33

bslatkin commented 5 years ago

This is going to be out of scope in future releases because it doesn't apply to Python 3.