4
$\begingroup$

What scenarios would cause coroutines to be a better (i.e. more robust, easier to modify) answer than simple mutable objects?

For example, in Fluent Python, the following running average example is used to show what coroutines can do:

def averager():
    total = 0.0
    count = 0
    average = None
    while True:
        term = yield average
        total += term
        count += 1
        average = total / count

Why not just use a class-based object?

class Averager:

    def __init__(self,):
        self.total = 0.0
        self.count = 0
        self.average = None

    def send(self, term):
        self.total += term
        self.count += 1
        self.average = self.total / self.count
        return self.average
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.