Ticket #4506: RegroupNode-groupby-v2.patch

File RegroupNode-groupby-v2.patch, 2.0 KB (added by (removed), 17 years ago)

updated version that works for py2.3 (added a native groupby equivalent).

  • django/template/defaulttags.py

    === modified file 'django/template/defaulttags.py'
     
    77import sys
    88import re
    99
     10try:
     11    from itertools import groupby
     12except ImportError:
     13    # we fall back to a simplified version of groupby, mainly for speed reasons.
     14    # for the 'official' version, pull it from
     15    # http://docs.python.org/lib/itertools-functions.html
     16
     17    def groupby(iterable, keyfunc=None):
     18        if keyfunc is None:
     19            keyfunc = lambda x:x
     20        iterable = iter(iterable)
     21        l = [iterable.next()]
     22        lastkey = keyfunc(l)
     23        for item in iterable:
     24            key = keyfunc(item)
     25            if key != lastkey:
     26                yield lastkey, l
     27                lastkey = key
     28                l = [item]
     29            else:
     30                l.append(item)
     31        yield lastkey, l
     32
    1033if not hasattr(__builtins__, 'reversed'):
    1134    # For Python 2.3.
    1235    # From http://www.python.org/doc/current/tut/node11.html
     
    252275        if obj_list == None: # target_var wasn't found in context; fail silently
    253276            context[self.var_name] = []
    254277            return ''
    255         output = [] # list of dictionaries in the format {'grouper': 'key', 'list': [list of contents]}
    256         for obj in obj_list:
    257             grouper = self.expression.resolve(obj, True)
    258             # TODO: Is this a sensible way to determine equality?
    259             if output and repr(output[-1]['grouper']) == repr(grouper):
    260                 output[-1]['list'].append(obj)
    261             else:
    262                 output.append({'grouper': grouper, 'list': [obj]})
    263         context[self.var_name] = output
     278        # list of dictionaries in the format {'grouper': 'key', 'list': [list of contents]}
     279        context[self.var_name] = [{'grouper':key, 'list':list(val)} for key, val in
     280            groupby(obj_list, lambda v, f=self.expression.resolve: f(v, True))]
    264281        return ''
    265282
    266283def include_is_allowed(filepath):
Back to Top