Yotam Vaknin writes:
Hi,
I am using groupby (from itertools) to group objects by a key. It would be very useful for me to be able to group objects by the relation of two consecutive objects or by an object relation to the first object in the current group.
I don't think you need to extend groupby. You can just cache the object to compare to. How about a decorator like def relate_to_first(is_related): def wrapped(this, _first=[]): if _first: if is_related(this, _first[0]): pass else: _first[0] = this _first[1] += 1 else: _first[0] = this _first[1] = 0 return _first[1] return wrapped @relate_to_first def some_relation(this, that): pass and similarly for a decorator relate_to_last? There are probably more elegant ways to do this, such as a class whose instances are callable. Such a class could also provide a reset method so you could reuse the relation Warning: that code is untested.