Search code examples
pythonpython-2.7python-3.xyield-keyword

How to convert version 3.x "yield from" to something compatible in version 2.7?


This works fine with Python 3.5 .I understand yield from is not available in python 2.7. How can I implement the depth_first() function using python 2.7?

The following solution did not help me: Converting "yield from" statement to Python 2.7 code

class Node:
 def __init__(self, value):
    self._value = value
    self._children = []

 def __repr__(self):
    return 'Node({!r})'.format(self._value)

 def add_child(self, node):
    self._children.append(node)

 def __iter__(self):
    return iter(self._children)

 def depth_first(self):
    yield self
    for c in self:
        yield from c.depth_first()

# Example
if __name__ == '__main__':
    root = Node(0)
    child1 = Node(1)
    child2 = Node(2)
    root.add_child(child1)
    root.add_child(child2)
    child1.add_child(Node(3))
    child1.add_child(Node(4))
    child2.add_child(Node(5))
    for ch in root.depth_first():
        print(ch)

This is the expected output:

Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)

Solution

  • Convert yield from into a for-loop with plain yield.

    Convert class Node: into class Node(object): to ensure you get a new-style class.

    The code now works in Python 2.7.

    class Node(object):
     def __init__(self, value):
        self._value = value
        self._children = []
    
     def __repr__(self):
        return 'Node({!r})'.format(self._value)
    
     def add_child(self, node):
        self._children.append(node)
    
     def __iter__(self):
        return iter(self._children)
    
     def depth_first(self):
        yield self
        for c in self:
            for n in c.depth_first():
                yield n
    
    # Example
    if __name__ == '__main__':
        root = Node(0)
        child1 = Node(1)
        child2 = Node(2)
        root.add_child(child1)
        root.add_child(child2)
        child1.add_child(Node(3))
        child1.add_child(Node(4))
        child2.add_child(Node(5))
        for ch in root.depth_first():
            print(ch)