views:

162

answers:

1

I am looking at some code that has a lot of sort calls using comparison functions, and it seems like it should be using key functions.

If you were to change seq.sort(lambda x,y: cmp(x.xxx, y.xxx)), which is preferable:

seq.sort(key=operator.attrgetter('xxx'))

or:

seq.sort(key=lambda a:a.xxx)

I would also be interested in comments on the merits of making changes to existing code that works.

+4  A: 

"Making changes to existing code that works" is how programs evolve;-). Write a good battery of tests that give known results with the existing code, save those results (that's normally known as "golden files" in a testing context); then make the changes, rerun the tests, and verify (ideally in an automated way) that the only changes to the tests' results are those that are specifically intended to be there -- no undesired or unexpected side effects. One can use more sophisticated quality assurance strategies, of course, but this is the gist of many "integration testing" approaches.

As for the two ways to write simple key= function, the design intent was to make operator.attrgetter faster by being more specialized, but at least in current versions of Python there's no measurable difference in speed. That being the case, for this special situation I would recommend the lambda, simply because it's more concise and general (and I'm not usually a lambda-lover, mind you!-).

Alex Martelli
i concur with alex's answer (that's he's no lambda lover) :-) but also second the notion of the lambda. in your example above, it may be a tiny bit faster because you don't have to look up either `operator` or `operator.attrgetter()`... you have the actual function object already! however, it is barely noticeable as alex has said already, but the `lambda` solution does win Python Zen points by being easier to read.
wescpy
Thanks, Alex and Wesley!
Paul McGuire