[Python-Dev] decorate-sort-undecorate

Raymond Hettinger raymond.hettinger at verizon.net
Mon Oct 13 15:34:15 EDT 2003

For Py2.4, I propose adding an optional list.sort() argument to support
the decorate-sort-undecorate pattern.
The current, pure Python approach to DSU is pure arcana.  It is obscure
enough and cumbersome enough that cmpfunc() tends to get used instead.
Built-in C support for DSU requires much less skill to use, results in
more readable code, and runs faster.
Raymond Hettinger
------ Concept demonstraton ------------------
def sort(self, cmpfunc=None, decorator=None):
    """Show how list.sort() could support a decorating function"""
    args = ()
    if cmpfunc is not None:
        args = (cmpfunc,)
    if decorator is None:
        aux = zip(map(decorator, self), self)   # Decorate
        self[:] = list(zip(*aux)[1])       # Un-decorate
a = 'the Quick brown Fox jumped Over the Lazy Dog'.split()
sort(a)                                # the no argument form is
print a, 'Normal sort'
sort(a, lambda x,y: -cmp(x,y))    # old code still works without change
print a, 'Reverse sort'
sort(a, decorator=str.lower)       # the new way is fast, clean, and
print a, 'Lowercase sort'
# The decorator form works especially well with mappings so that
# keys can be sorted by any field. 
ages = dict(john=5, amy=3, andrea=32, henry=12)
names = ages.keys()
location = dict(john='alaska', amy='spain', andrea='peru', henry='iowa')
print names, '<-- by name'
sort(names, decorator=ages.__getitem__)
print names, '<-- by age'
sort(names, decorator=location.__getitem__)
print names, '<-- by location'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-dev/attachments/20031013/a4413f54/attachment.html

More information about the Python-Dev mailing list