请求示例代码以了解 return 值的协程中 throw() 的 return 值
Ask for a sample code to understand the return value of throw() in a coroutine which returns values
"Python Essential Reference (Fourth Edition)" 一书在第 106 页谈到 return 协程的 throw() 值,returns 值,即在 yield 语句中同时接收和发射:
我正在尝试编写一个示例代码来查看 throw() 函数在所描述情况下的 return 值是否为 "the value passed to the next yield"。以下是我到目前为止编写的示例代码:
def line_splitter(delimiter=None):
print("Ready to split")
result = None
try:
while True:
line = (yield result)
result = line.split(delimiter)
except GeneratorExit:
print("Receiver done")
except RuntimeError:
print "RuntimeError captured"
s = line_splitter(",")
s.next()
s.send("A,B,C")
r=s.throw(RuntimeError,"You're hosed!")
问题是,当我 运行 最后一行在协程中使用 throw() 引发异常时,RuntimeError 被按预期捕获,但也生成了 StopIteration 异常并传播了此异常向外所以我无法得到结果 throw() returns。那么,如何修改我现有的示例代码来验证文中的语句:"If you raise an exception in a coroutine using throw(), the value passed to the next yield in the coroutine will be returned as the result of throw()"?非常感谢。
PS: 我正在使用 python 2.7.12
如果你 'run out of yield
s' 提出 StopIteration
。一个简单的(但荒谬的?)解决方法是 yield
异常(或其他任何东西)返回:
def line_splitter(delimiter=None):
print("Ready to split")
result = None
try:
while True:
line = yield result
result = line.split(delimiter)
except GeneratorExit as exc:
print("Receiver done")
yield exc
except RuntimeError as exc:
print("RuntimeError captured")
yield exc
s = line_splitter(",")
next(s)
s.send("A,B,C")
r=s.throw(RuntimeError,"You're hosed!")
print(r)
"Python Essential Reference (Fourth Edition)" 一书在第 106 页谈到 return 协程的 throw() 值,returns 值,即在 yield 语句中同时接收和发射:
我正在尝试编写一个示例代码来查看 throw() 函数在所描述情况下的 return 值是否为 "the value passed to the next yield"。以下是我到目前为止编写的示例代码:
def line_splitter(delimiter=None):
print("Ready to split")
result = None
try:
while True:
line = (yield result)
result = line.split(delimiter)
except GeneratorExit:
print("Receiver done")
except RuntimeError:
print "RuntimeError captured"
s = line_splitter(",")
s.next()
s.send("A,B,C")
r=s.throw(RuntimeError,"You're hosed!")
问题是,当我 运行 最后一行在协程中使用 throw() 引发异常时,RuntimeError 被按预期捕获,但也生成了 StopIteration 异常并传播了此异常向外所以我无法得到结果 throw() returns。那么,如何修改我现有的示例代码来验证文中的语句:"If you raise an exception in a coroutine using throw(), the value passed to the next yield in the coroutine will be returned as the result of throw()"?非常感谢。
PS: 我正在使用 python 2.7.12
如果你 'run out of yield
s' 提出 StopIteration
。一个简单的(但荒谬的?)解决方法是 yield
异常(或其他任何东西)返回:
def line_splitter(delimiter=None):
print("Ready to split")
result = None
try:
while True:
line = yield result
result = line.split(delimiter)
except GeneratorExit as exc:
print("Receiver done")
yield exc
except RuntimeError as exc:
print("RuntimeError captured")
yield exc
s = line_splitter(",")
next(s)
s.send("A,B,C")
r=s.throw(RuntimeError,"You're hosed!")
print(r)