2

有没有办法在 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
4

3 回答 3

2

这是你想要的吗?

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
于 2013-04-26T15:24:14.450 回答
2

是的; 生成器在实际迭代之前不会运行,因此您可以将迭代已履行的承诺的值推迟到请求之前:

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)
于 2013-04-26T15:26:13.320 回答
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
于 2013-04-26T15:24:10.313 回答