Add callable sort key functionality to sort_keys #666
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently any truthy value of
sort_keys
will send the mapping pairs throughsorted()
before representing the mapping. This PR extends that functionality so that callable values ofsort_keys
will be passed as thekey
parameter ofsorted()
. 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:
sort_keys = lambda k: k.upper()
for a case insensitive sort that I expect to make more sense to a human reader.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 asx[0]
instead of justx
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.