# second version: we use GeneratorExit to stop # no more need for a method, hence no need for a class def accumulator(batch_size): try: while True: batch = [] for c in range(batch_size): received = yield batch.append(received) print('flush', batch) except GeneratorExit: print('flush', batch) it = accumulator(batch_size=3) next(it) # prime it for i in range(10): it.send(i) it.close() # raises GeneratorExit inside the generator