[Python-ideas] Cofunctions/yield from -> fibers

Scott Dial scott+python-ideas at scottdial.com
Fri Aug 13 08:52:47 CEST 2010

On 8/13/2010 1:35 AM, Nick Coghlan wrote:
> On Fri, Aug 13, 2010 at 3:07 PM, geremy condra <debatem1 at gmail.com> wrote:
>> I won't pretend to understand the current discussion or its
>> motivation, but I know I would appreciate it if examples of the
>> obvious-and-straightforward variety were added.
> Yes, it would be nice if PEP 380's generator delegation forest didn't
> get lost in the cofunction trees :)

Yes, I think even something as trivial as an example in-order iteration
over a binary tree should be included since it is accessible and the
benefits of readability, efficiency, and correctness are apparent:

class BinaryTree:
    def __init__(self, left=None, us=None, right=None):
        self.left = left
        self.us = us
        self.right = right

    def __iter__(self):
        if self.left:
            yield from self.left
        if self.us:
            yield self.us
        if self.right:
            yield from self.right

You can point out that "yield from" prevents a recursion depth problem
while also being agnostic to whether left/right is also a BinaryTree
object (e.g., a tuple or list or some other user-defined type works just
as well as an iterable leaf) -- a feat that would be rather complicated
and verbose otherwise. As a bonus, the run-time of such an iteration is
faster due to the flattening optimization that is only possible with
special syntax.

Scott Dial
scott at scottdial.com
scodial at cs.indiana.edu

More information about the Python-ideas mailing list