[Python-ideas] Revised^4 PEP on yield-from

Adam Olsen rhamph at gmail.com
Fri Feb 20 02:16:45 CET 2009


On Thu, Feb 19, 2009 at 5:53 PM, Guido van Rossum <guido at python.org> wrote:
> Hey Greg, I think your efforts now should be focused on the
> implementation and not on continued arguing with unbelievers. Code
> speaks.

Speaking of code...

# trampoline implementation
class trampoline(object):
    def __init__(self, func, instance=None):
        self.func = func
        self.instance = instance
    def __get__(self, obj, type=None):
        return trampoline(self.func, obj)
    def __call__(self, *args, **kwargs):
        if self.instance is not None:
            args = (self.instance,) + args
        return trampolineiter(self.func(*args, **kwargs))

class trampolineiter(object):
    def __init__(self, iterable):
        self.stack = [iterable]
    def __iter__(self):
        return self
    def next(self):
        while True:
            try:
                x = self.stack[-1].next()
            except StopIteration:
                self.stack.pop(-1)
                if not self.stack:
                    raise
            else:
                if isinstance(x, trampolineiter):
                    assert len(x.stack) == 1
                    self.stack.append(x.stack[0])
                elif isinstance(x, leaf):
                    return x.data
                else:
                    raise TypeError("Unexpected type yielded to trampoline")

class leaf(object):
    def __init__(self, data):
        self.data = data


# Example usage
class Tree(object):
    def __init__(self, name, left, right):
        self.name = name
        self.left = left
        self.right = right
    @trampoline
    def __iter__(self):
       if self:
           yield leaf(self)
           yield traverse(self.left)
           yield traverse(self.right)

>>> mytree = Tree(0, Tree(1, None, Tree(2, None, None)), Tree(3, None, None))
>>> for node in mytree:
...     print "Found:", node.name
...
Found: 0
Found: 1
Found: 2
Found: 3

-- 
Adam Olsen, aka Rhamphoryncus



More information about the Python-ideas mailing list