当 Guido talked 时我去了 SF Python 聚会关于 Tulip,Python 中用于异步操作的 future asyncIO 库。
要点是,如果你想异步运行某些东西,你可以使用 "yield from"+ expression
和几个装饰器来指定对 之后的调用yield from
应该异步执行。它的好处是您可以正常读取该函数中的语句(就好像它是同步的)并且它的行为就好像它在该函数的执行方面是同步的(返回值和错误/异常传播和处理).
我的问题是:为什么不采用相反的行为,即默认情况下所有函数调用都是异步的(并且没有 yield from
)并且在您想要执行某些操作时使用不同的显式语法同步?
(除了需要另一个关键字/语法规范)
最佳答案
真正的答案是 Guido 喜欢异步屈服点在协程中是显式的这一事实,因为如果您没有意识到调用可以屈服,那么这就是并发问题的诱因——就像线程一样。但是,如果您必须编写一个显式的 yield from
,则很容易确保它不会落在两个关键操作的中间,这两个关键操作对于其余代码来说应该是原子的。
正如他提到的 in his PyCon 2013 keynote ,还有其他的 Python 异步框架,比如 Gevent,默认是异步的,他不喜欢那种做法。 (在 11:58):
And unfortunately you're still not completely clear of the problem that the scheduler could at a random moment interrupt your task and switch to a different one. [...] Any function that you call today that you happen to know that it never switches, tomorrow someone could add a logging statement or a lazy caching or a consulting of a settings file. [...]
关于python - 郁金香/异步IO : why not all calls be async and specify when things should be synchronous?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19471967/