在Python函数上使用协程必须要做什么? [英] What are the things you have to use coroutines over functions in Python?

查看:98
本文介绍了在Python函数上使用协程必须要做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在发现Python协程,这很有意义。我了解它们是具有多个入口和出口点的更通用功能,并且可以将值返回给不同的接收器。但是,谁能在何时,为何要比常规功能上更喜欢协程呢?

I am discovering Python coroutines and it makes a lot of sense. I understand they are more "general" functions with multiple entry and exit points and can return value to different receivers. But who can give a summary when and why coroutines are prefered over regular functions?

推荐答案

为您的用例创建比常规函数更容易创建的应用。这实际上可能意味着许多不同的事情,所以这里是一个示例:

When they're easier to create for your use case than regular functions. This may mean many different things really, so here's one example:

您有一个可以读取和发送数据的服务器,但是您正在实现的协议中州。现在,您有2个选择:

You've got a server which reads and sends data, but you're implementing a protocol which has some state. Now you've got 2 options:

使状态显式并将其保留在某个对象中,然后最终得到这样的设计:

Make the state explicit and keep it in some object, then you end up with a design like:

class ClientConnection():
    def __init__(self):
        self.current_state = START

    def new_data(self, data):
        if self.current_state == START:
            self.current_state = do_auth(data)
        elif self.current_state == SOMETHING_ELSE:
            self.current_state = do_something_else(data)
        elif ...

或者隐含状态并输入相同的函数一遍又一遍:

Or make the state implicit and just enter the same function over and over again:

def connection(self):
    auth_data = yield
    if not do_auth(auth_data):
        raise something

    more_data = yield(AUTH_OK)
    yield from do_something_else(more_data)
    ...

现在,如果您有一个庞大的状态机,并且流量不是微不足道的t选项可能更好。如果您的情况较简单(身份验证,获取命令,发送结果),则第二种选择可能更好。

Now if you have a huge state machine and the flow is not trivial, the first option may be better. If you have an simpler case (auth, get command, send results), the second option may be better.

这篇关于在Python函数上使用协程必须要做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆