Python 协程可以在不先执行 `next` 的情况下 `send` 吗?
Python coroutine can one `send` without first doing `next`?
向 generator/coroutine 发送值时,有没有办法避免初始 next(g)
?
def gen(n):
m = (yield) or "did not send m to gen"
print(n, m)
g = gen(10)
next(g)
g.send("sent m to g") # prints "10 sent m to g"
没有next(g)
,我们得到
TypeError: can't send non-None value to a just-started generator
错误源于 CPython 的 gen_send_ex2
中的 this bit of code,即如果 gi_frame_state
是 FRAME_CREATED
。
本次讨论中设置 gi_frame_state
的唯一重要位置是 here in gen_send_ex2
, after a (possibly None) value has been sent and a frame is about to be evaluated。
基于此,我会说不,无法将 non-None 值发送到 just-started 生成器。
不确定这对您的具体情况是否有帮助,但您可以使用装饰器来初始化协程。
def initialized(coro_func):
def coro_init(*args, **kwargs):
g = coro_func(*args, **kwargs)
next(g)
return g
return coro_init
@initialized
def gen(n):
m = (yield) or "did not send m to gen"
print(n, m)
g = gen(10)
g.send("sent m to g") # prints "10 sent m to g"
向 generator/coroutine 发送值时,有没有办法避免初始 next(g)
?
def gen(n):
m = (yield) or "did not send m to gen"
print(n, m)
g = gen(10)
next(g)
g.send("sent m to g") # prints "10 sent m to g"
没有next(g)
,我们得到
TypeError: can't send non-None value to a just-started generator
错误源于 CPython 的 gen_send_ex2
中的 this bit of code,即如果 gi_frame_state
是 FRAME_CREATED
。
本次讨论中设置 gi_frame_state
的唯一重要位置是 here in gen_send_ex2
, after a (possibly None) value has been sent and a frame is about to be evaluated。
基于此,我会说不,无法将 non-None 值发送到 just-started 生成器。
不确定这对您的具体情况是否有帮助,但您可以使用装饰器来初始化协程。
def initialized(coro_func):
def coro_init(*args, **kwargs):
g = coro_func(*args, **kwargs)
next(g)
return g
return coro_init
@initialized
def gen(n):
m = (yield) or "did not send m to gen"
print(n, m)
g = gen(10)
g.send("sent m to g") # prints "10 sent m to g"