1def gen():
2    i = 0
3    while 1:
4        yield i
5        i += 1
6
7g = gen()
8
9try:
10    g.pend_throw
11except AttributeError:
12    print("SKIP")
13    raise SystemExit
14
15
16# Verify that an injected exception will be raised from next().
17print(next(g))
18print(next(g))
19g.pend_throw(ValueError())
20
21v = None
22try:
23    v = next(g)
24except Exception as e:
25    print("raised", repr(e))
26
27print("ret was:", v)
28
29
30# Verify that pend_throw works on an unstarted coroutine.
31g = gen()
32g.pend_throw(OSError())
33try:
34    next(g)
35except Exception as e:
36    print("raised", repr(e))
37
38
39# Verify that you can't resume the coroutine from within the running coroutine.
40def gen_next():
41    next(g)
42    yield 1
43
44g = gen_next()
45
46try:
47    next(g)
48except Exception as e:
49    print("raised", repr(e))
50
51
52# Verify that you can't pend_throw from within the running coroutine.
53def gen_pend_throw():
54    g.pend_throw(ValueError())
55    yield 1
56
57g = gen_pend_throw()
58
59try:
60    next(g)
61except Exception as e:
62    print("raised", repr(e))
63
64
65# Verify that the pend_throw exception can be ignored.
66class CancelledError(Exception):
67    pass
68
69def gen_cancelled():
70    for i in range(5):
71        try:
72            yield i
73        except CancelledError:
74            print('ignore CancelledError')
75
76g = gen_cancelled()
77print(next(g))
78g.pend_throw(CancelledError())
79print(next(g))
80# ...but not if the generator hasn't started.
81g = gen_cancelled()
82g.pend_throw(CancelledError())
83try:
84    next(g)
85except Exception as e:
86    print("raised", repr(e))
87
88
89# Verify that calling pend_throw returns the previous exception.
90g = gen()
91next(g)
92print(repr(g.pend_throw(CancelledError())))
93print(repr(g.pend_throw(OSError)))
94
95
96# Verify that you can pend_throw(None) to cancel a previous pend_throw.
97g = gen()
98next(g)
99g.pend_throw(CancelledError())
100print(repr(g.pend_throw(None)))
101print(next(g))
102