#NEWLINE# def group_select( selects , length = None , depth = None ) : #NEWLINE# #INDENT# '\n    Given a list of key tuples to select, groups them into sensible\n    chunks to avoid duplicating indexing operations.\n    ' #NEWLINE# if ( ( length == None ) and ( depth == None ) ) : #NEWLINE# #INDENT# length = depth = len ( selects [ 0 ] ) #NEWLINE# #UNINDENT# getter = operator . itemgetter ( ( depth - length ) ) #NEWLINE# if ( length > 1 ) : #NEWLINE# #INDENT# selects = sorted ( selects , key = getter ) #NEWLINE# grouped_selects = defaultdict ( dict ) #NEWLINE# for ( k , v ) in itertools . groupby ( selects , getter ) : #NEWLINE# #INDENT# grouped_selects [ k ] = group_select ( list ( v ) , ( length - 1 ) , depth ) #NEWLINE# #UNINDENT# return grouped_selects #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# return list ( selects )