Last week, I wrote about how Python 2's cmp() function could be used to extract the positive, neutral, or negative sign of a number. At the time, I had wanted access to cmp() to determine the direction an object needed to travel in this year's Day 9 of Advent of Code, but the function was removed from Python 3 to better unify its various comparison functions.

As luck would have it, I needed another version of cmp() for the Day 13 challenge as well. I had coded a non-trivial comparison function according to the problem's arbitrary rules and needed to use it to order several "packets" provided as input. Sure, I could've written my own sort function to accomplish this, but the reason I'm a great programmer is because I'm lazy. I missed the pure simplicity of coding this up in Python 2:


In Python 3, the list-sorting function no longer accepts a cmp argument. However, the function's key parameter still exists! Better yet, Python's documentation for it reveals that the core developers helpfully wrote a transformation function so that a custom comparison function could be passed in as an argument to the key parameter!

It works like this:

from functools import cmp_to_key


And that's pretty simple too. Good to know I can stay lazy.