What Are The Things You Have To Use Coroutines Over Functions In 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
Solution 1:
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:
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:
classClientConnection():
def__init__(self):
self.current_state = START
defnew_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:
defconnection(self):
auth_data = yieldifnot do_auth(auth_data):
raise something
more_data = yield(AUTH_OK)
yieldfrom do_something_else(more_data)
...
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.
Post a Comment for "What Are The Things You Have To Use Coroutines Over Functions In Python?"