coroutine.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 from __future__ import division
3 
4 from functools import wraps
5 from UserDict import IterableUserDict
6 
7 def coroutine(func):
8  @wraps(func)
9  class wrapper(IterableUserDict):
10  def __init__(self,*args,**kwargs):
11  self.target = None
12  self.func = func
13  self.data = dict()
14  self.cr = self.func(self,*args,**kwargs)
15  self.initialized = False
16 
17  def __or__(self, other):
18  o = self._getLast()
19  o.target = other
20  self.ref(other)
21  return self
22 
23  def ref(self,other):
24  a = other
25  while a is not None:
26  a.data = self.data
27  a = a.target
28 
29  def _getLast(self):
30  o = self
31  while o.target!=None:
32  o = o.target
33  return o
34 
35  # send to next target
36  def __call__(self,*args,**kwargs):
37  if self.target!=None:
38  self.target.send(*args,**kwargs)
39 
40  def send(self,*args,**kwargs):
41  if not self.initialized:
42  self.cr.next()
43  self.initialized = True
44  if len(args)==0:
45  self.cr.send(None)
46  else:
47  self.cr.send(*args)
48 
49  def close(self):
50  self.cr.close()
51 
52  return wrapper
53 
54 
55 # Example use
56 if __name__ == '__main__':
57 
58  @coroutine
59  def printer(send):
60  while True:
61  s = (yield)
62  print s
63  send(s)
64 
65  @coroutine
66  def plus(send,a):
67  while True:
68  v = (yield)
69  send(v+a)
70 
71  @coroutine
72  def plusconst(send,n):
73  while True:
74  d = (yield)
75  c = send['const']
76  send(d+c)
77 
78 
79  p = plus(3) | plus(2) | printer()
80  p.send(1)
81 
82  p = plus(3) | printer() | plusconst('const') | printer()
83  p['const'] = 5
84 
85  p.send(2)
type(dict_typ) function, pointer, public dict(n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14, n15, n16, n17, n18, n19, n20)
Construct a new dictionary from several key/value pairs. Together with the Assign subroutine and over...
def plus(send, a)
Definition: coroutine.py:66
def printer(send)
Definition: coroutine.py:59
def coroutine(func)
Definition: coroutine.py:7
def plusconst(send, n)
Definition: coroutine.py:72