#!/usr/bin/env python # -*- coding: utf-8 -*- import gc import itertools def grouper(iterable, chunksize): """ Return elements from the iterable in `chunksize`-ed lists. The last returned element may be smaller (if length of collection is not divisible by `chunksize`). >>> print list(grouper(xrange(10), 3)) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] """ i = iter(iterable) while True: chunk = list(itertools.islice(i, int(chunksize))) if not chunk: break yield chunk ########## Solution, comment out to test original def grouper(iterable, chunksize): i = iter(iterable) while True: tmpr = [list(itertools.islice(i, int(chunksize)))] if not tmpr[0]: break yield tmpr.pop() class ReportingFree(object): def __del__(self): print('Freed ' + str(id(self))) def createObjects(): while True: yield ReportingFree() g = grouper(createObjects(), 3) gc.collect() print(gc.get_referrers(next(g))) gc.collect() # We're now after yield, but before the next iteration print('Finished')