用于使用回调恢复代码的库。
resumeback的Python项目详细描述
使用回调恢复代码的python库。
resumeback提供实用函数decorator 支持使用基于回调的接口的 在中,一行执行 –单一功能。
这里有完整的文档:http://fichtefoll.github.io/resumeback/
安装
$ pip install resumeback
用法
resumeback.send_self发送生成器函数的机制 自己的把柄 是为了更好地控制流量 使用基于回调的接口。 本质上,它支持一行执行。
下面是一个使用异步回调机制的函数 表示已进行用户输入:
fromthreadingimportThreaddefask_for_user_input(question,on_done):defwatcher():result=input(question)on_done(result)Thread(target=watcher).start()
使用像ask_for_user_input这样的函数的传统方式是 以某种方式定义函数, 要么作为闭包,要么使用functools.partial,以便我们可以保留 在执行上述函数之前我们已经积累的状态。
例如这样:
defmain():arbitrary_value=10defon_done(number):number=str(number)print("Result:",number*arbitrary_value)ask_for_user_input("Please enter a number",on_done)
因为python没有多行内联函数, 这很尴尬, 因为我们从^{tt3}的函数调用中跳出$ 回到我们以前定义的函数on_done –在这种情况下只能调用一次。
但是,使用resumeback.send_self, 我们可以做些什么来使我们的执行线变平 通过在原始函数中传递回调以恢复执行:
fromresumebackimportsend_self@send_selfdefmain():this=yield# "this" is now a reference to the just-created generatorarbitrary_value=10# Yield pauses execution until one of the generator methods is called,# such as `.send`, which we provide as the callback parameter.number=yieldask_for_user_input("Please enter a number",this.send)number=str(number)print("Result:",number*arbitrary_value)
致谢
项目最初在来自@Varriount的forum post之后启动 在崇高的文本论坛上。 我只是把他的想法“提升到下一个(抽象)层次” 更方便使用。