在创建python生成器后更新它

时间:2013-04-26 15:12:28

标签: python python-2.7 generator

有没有办法在python 2.7中做这样的事情?

def scaleit(g, k):
  for item in g:
    yield item*k

promise = ??????
# defines a generator for reference but not use:
# other functions can make use of it,
# but it requires a call to promise.fulfill() to
# define what the generator is going to yield;
# promise raises an error if next() is called 
# before the promise is fulfilled

f = scaleit(promise, 3)
promise.fulfill(range(10))

for item in f:
  print item

3 个答案:

答案 0 :(得分:2)

是;生成器在实际迭代之前不会运行,因此您可以推迟迭代已满足的promise的值,直到请求为止:

class Promise(object):
    def fulfill(self, result):
        self.result = result
    def __iter__(self):
        return iter(self.result)

def scaleit(g, k):
  for item in g:
    yield item*k

promise = Promise()
f = scaleit(promise, 3)
promise.fulfill(range(10))
print list(f)

答案 1 :(得分:1)

我认为你想在生成器上使用send()方法:

def gen():
    reply = yield None
    if not reply:  # reply will be None if send() wasn't called
        raise ValueError("promise not fulfilled")
    yield 5

g1 = gen()
next(g1)  # advance to the first yield
g1.send(True)
print(next(g1))  # prints 5

g2 = gen()
next(g2)
# forget to send
print(next(g2))  # raises ValueError

答案 2 :(得分:1)

这是你想要的吗?

def scaleit(g, k):
  for item in g:
    yield item * k

class Promise(object):
    def __init__(self):
        self.g = None

    def fulfill(self, g):
        self.g = iter(g)

    def __iter__(self):
        return self

    def next(self):
        return next(self.g)

promise = Promise()

f = scaleit(promise, 3)
promise.fulfill(range(10))

for item in f:
  print item