On Wed, 2006-04-05 at 17:44 -0400, Muness Alrubaie wrote:
> From: Matthew Good <[EMAIL PROTECTED]>
> >
> > On Wed, 2006-04-05 at 16:10 -0400, Muness Alrubaie wrote:
> > > On a different note, the sorted implementation in util.py is bit less
> > > handy than it should be, methinks. Here's a patch that works (at
> > > least for my needs):
> > >
> > > - def sorted(iterable, cmp=None, key=None, reverse=False):
> > > + def sorted(iterable, cmp=None, key=str, reverse=False):
> > > """Partial implementation of the "sorted" function from Python
> > > 2.4"""
> > > lst = [(key(i), i) for i in iterable]
> > > lst.sort()
> >
> > This method is meant give the same result as "sorted" in Python 2.4 for
> > the implemented parameters ("key" and "reverse"), so "str" cannot be the
> > default for "key". If you need to sort values based on their string
> > representation you'll need to explicitly pass the parameter.
>
> The current sorted implementation throws an exception if no key
> function is passed unlike Python 2.4 which doesn't require a key
> function to work properly. It seemed like a default key of str was
> reasonable if none was passed in. I am a newbie to Python and just
> used the first thing that seemed reasonable to me.
>
> What might be a more compatible function?
Well, if there's no key you can skip most of the logic for sorting on
the key:
if key is None:
lst = list(iterable)
lst.sort()
return lst
I hadn't bothered to add this before since I added "sorted" primarily to
replace the situations where Trac previously used a custom comparison
method. If it's useful I can make Trac's "sorted" implementation more
complete.
Also, if you already have a list, sort it in place if possible:
"lst.sort()". Using "sorted" will copy the existing list, so it's less
efficient. If you're sorting an iterator/generator then "sorted" is
convenient.
--
Matthew Good <[EMAIL PROTECTED]>
_______________________________________________
Trac mailing list
[email protected]
http://lists.edgewall.com/mailman/listinfo/trac