-
Notifications
You must be signed in to change notification settings - Fork 1
/
tornado_style.py
67 lines (46 loc) · 1.35 KB
/
tornado_style.py
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
# -*- coding: utf-8 -*-
from backports_abc import Generator as GeneratorType
class Return(Exception):
def __init__(self, value=None):
self.value = value
def coroutine(func):
def wrapper(*args, **kwargs):
def _dispatch(yielded):
if isinstance(yielded, GeneratorType):
return _execute_yield(yielded)
else:
return _send(yielded)
def _send(yielded):
try:
yielded = origin_gen.send(yielded)
return _dispatch(yielded)
except (StopIteration, Return) as e:
return getattr(e, 'value', None)
except Exception as error:
print 'terrible error happened: %r' % error
def _execute_yield(gen):
yielded = next(gen)
return _dispatch(yielded)
result = func(*args, **kwargs)
origin_gen = result
return _execute_yield(result)
return wrapper
def get_value2():
return 10086
def get_value1():
yield get_value2()
@coroutine
def test():
value1 = yield get_value1()
print 'got value1: %d' % value1
value2 = yield get_value2()
print 'got value2: %d' % value2
raise Return(value1 == value2)
if __name__ == '__main__':
result = test()
print result
"""
>>> got value1: 10086
>>> got value2: 10086
>>> True
"""