저는 소비자 생성기의 파이프 라인을 가지고 있습니다. 이 소비자들 중 마지막 순간부터 어느 시점에서 결과를보고 싶습니다. 작동 방식 :소비자 생성기에서 단일 값 반환
class StopIterationWithResult(StopIteration):
def __init__(self, result):
super(StopIterationWithResult, self).__init__()
self.result = result
# for definition fo consumer decorator see http://www.python.org/dev/peps/pep-0342/
@consumer
def waitfor3():
while True:
value = (yield)
if value == 3:
raise StopIterationWithResult('Hello')
c = waitfor3()
for i in range(10):
try:
print 'calling', i
c.send(i)
except StopIterationWithResult as r:
print 'stopped', r.result
break
더 좋은 방법이 있습니까? 예를 들어, return
문 때문에 StopIteration
이 발생하면 반환 값을 액세스 할 수 있습니까?
은 @alexis의 요청에 따라, 여기에 파이프 라인의 예입니다 :
class StopIterationWithResult(StopIteration):
def __init__(self, result):
super(StopIterationWithResult, self).__init__()
self.result = result
@consumer
def add1_filter(consumer):
while True:
value = (yield)
consumer.send(value+1)
@consumer
def waitfor3():
while True:
value = (yield)
print 'got', value
if value == 3:
raise StopIterationWithResult('Hello')
c = waitfor3()
f = add1_filter(c)
for i in range(10):
try:
print 'calling', i
f.send(i)
except StopIterationWithResult as r:
print 'stopped', r.result
break
그리고 여기 @Martijn 피에 터스에 의해 대답과 동일합니다 -하게 필터 좀 더 추한하지만 :
@consumer
def add1_filter(consumer):
result = None
while True:
value = (yield result)
result = consumer.send(value+1)
@consumer
def waitfor3():
while True:
value = (yield)
print 'got', value
if value == 3:
yield 'Hello'
break
c = waitfor3()
f = add1_filter(c)
r = None
for i in range(10):
try:
print 'calling', i
r = f.send(i)
except StopIteration:
print 'stopped', r
break
가 이해가 안 3' 후 정기적'StopIteration' 인상 : http://docs.python.org/2/library/exceptions.html#exceptions.BaseException 참조하십시오. – kreativitea
예를 들어 파이프 라인을 사용할 수 있습니까? 개선 할 것이없는 개선을 제안하는 것은 어렵습니다. – alexis