Python .send () support for class?

Writing a class, how do I implement

foo.send (item)?

__iter__ allows you to iterate through a class, like a generator, what if I want it to be a coroutine?

+6
python coroutine class
source share
1 answer

Here is a basic example of a coroutine :

 def coroutine(func): def start(*args,**kwargs): cr = func(*args,**kwargs) cr.next() return cr return start @coroutine def grep(pattern): print "Looking for %s" % pattern while True: line = (yield) if pattern in line: print(line) g = grep("python") # Notice how you don't need a next() call here g.send("Yeah, but no, but yeah, but no") g.send("A series of tubes") g.send("python generators rock!") # Looking for python # python generators rock! 

We can create a class that contains such a coroutine and delegates its call to the send method in the coroutine:

 class Foo(object): def __init__(self,pattern): self.count=1 self.pattern=pattern self.grep=self._grep() @coroutine def _grep(self): while True: line = (yield) if self.pattern in line: print(self.count, line) self.count+=1 def send(self,arg): self.grep.send(arg) foo = Foo("python") foo.send("Yeah, but no, but yeah, but no") foo.send("A series of tubes") foo.send("python generators rock!") foo.pattern='spam' foo.send("Some cheese?") foo.send("More spam?") # (1, 'python generators rock!') # (2, 'More spam?') 

Note that foo acts like a coroutine (since it has a submit method), but it is a class - it can have attributes and methods that can interact with the coroutine.

For more information (and great examples), see David Beazley Curious Course on Corouts and Concurrency.

+6
source share

All Articles