pyyaml icon indicating copy to clipboard operation
pyyaml copied to clipboard

Add callable sort key functionality to sort_keys

Open sparr opened this issue 2 years ago • 0 comments

Currently any truthy value of sort_keys will send the mapping pairs through sorted() before representing the mapping. This PR extends that functionality so that callable values of sort_keys will be passed as the key parameter of sorted(). A test is included for coverage and illustration purposes.

For my own purposes, I have a few use cases in mind, each to be applied in different scenarios:

  1. sort_keys = lambda k: k.upper() for a case insensitive sort that I expect to make more sense to a human reader.
  2. Similar to the test example, but with explicit ordering of the "sort first" keys, so I can get critical keys like "name" and "path" to the top where a human reader will see them first.
  3. Sorting based on the length/size of the value (not key) so longer dicts/arrays don't interrupt the visual flow of shorter values

This introduces a minor naming confusion issue, in that the sort applies not just to the keys but to (key,value) pairs produced by .items(). That was always the case, but wouldn't have been noticeable previously since dict keys are unique so values were never considered as part of the default sort. This requires sort_keys functions to access the key as x[0] instead of just x which may be counterintuitive. This could be avoided by passing only the keys to the key function instead of the pairs, but that would break my third use case above.

sparr avatar Sep 20 '22 15:09 sparr