开发者

Can I express this as a generator / coroutine?

开发者 https://www.devze.com 2023-03-14 21:32 出处:网络
Suppose I have the following class: class MyGen(object): def next(self): return X() def send(self, x): return f(x)

Suppose I have the following class:

class MyGen(object):
  def next(self):
    return X()

  def send(self, x):
    return f(x)

Is it possible to express it as a single function, using the yield keyword? Suppose I have g = MyGen(). Note that g.next() shouldn't call f(), and g.send(x) shouldn't call X(), b开发者_Python百科ut f() and X() could share some code.


This code will be almost equivalent:

def my_gen(x=None):
    while True:
        if x is None:
            x = yield X()
        else:
            x = yield f(x)

One difference is that you can't send a value (other than None) to a generator before calling next() for the first time. Another difference is that sending None won't trigger calling f(), since the generator can't distinguish send(None) and next().


Sven's formulation is exactly the way to go, I just wanted to add that if you want to know more about generators, coroutines and such in Python, this site is the place to go.

0

精彩评论

暂无评论...
验证码 换一张
取 消