pinnwand

bpaste has migrated platforms. We now support self removal of pastes and will automatically import pastes from our old software for the following 2 months (that is, until the end of november 2014).

If you have any pastes you'd like to preserve please visit their URLs and they will be automatically imported with no expiry.

This paste never expires. Pasted by import. View raw.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from greenlet import greenlet

# -------------- begin support code

class genlet(greenlet):

    def __init__(self, *args, **kwds):
        self.args = args
        self.kwds = kwds

    def run(self):
        fn, = self.fn
        fn(*self.args, **self.kwds)

    def __iter__(self):
        return self

    def __next__(self):
        self.parent = greenlet.getcurrent()
        result = self.switch()
        if self:
            return result
        else:
            raise StopIteration

    # Hack: Python < 2.6 compatibility
    next = __next__

    @classmethod
    def _getgenlet(cls):
        g = greenlet.getcurrent()
        while not isinstance(g, cls):
            if g is None:
                raise RuntimeError('yield outside a genlet')
            g = g.parent
        return g

def Yield(value):
    genlet._getgenlet().parent.switch(value)

def YieldFrom(gen):
    g = genlet._getgenlet()
    for value in gen:
        g.parent.switch(value)

def generator(func):
    class generator(genlet):
        fn = (func,)
    return generator

# -------------- end support code

if __name__ == "__main__":

    @generator
    def g(n):
        for i in range(n):
            Yield(i)

    @generator
    def f():
        YieldFrom(g(5))

    # direct use of a generator
    for i in g(5):
        print i

    # using a generator that forwards from another
    for i in f():
        print i