summaryrefslogtreecommitdiff
path: root/coverage/misc.py
diff options
context:
space:
mode:
authorNed Batchelder <ned@nedbatchelder.com>2021-10-12 08:46:25 -0400
committerNed Batchelder <ned@nedbatchelder.com>2021-10-12 08:46:25 -0400
commit0eaeb99f2de1330a562752d30d02d1898f681cf8 (patch)
treed51b41a302dddafd3092c0fc367b1676bab56a6d /coverage/misc.py
parent5b6b6ecb87f4aa1145977b1a4c8359b202da0d7a (diff)
downloadpython-coveragepy-git-0eaeb99f2de1330a562752d30d02d1898f681cf8.tar.gz
fix: use human sorting on human-readable things
Diffstat (limited to 'coverage/misc.py')
-rw-r--r--coverage/misc.py31
1 files changed, 31 insertions, 0 deletions
diff --git a/coverage/misc.py b/coverage/misc.py
index 29397537..40f00930 100644
--- a/coverage/misc.py
+++ b/coverage/misc.py
@@ -389,3 +389,34 @@ def import_local_file(modname, modfile=None):
spec.loader.exec_module(mod)
return mod
+
+
+def human_key(s):
+ """Turn a string into a list of string and number chunks.
+ "z23a" -> ["z", 23, "a"]
+ """
+ def tryint(s):
+ """If `s` is a number, return an int, else `s` unchanged."""
+ try:
+ return int(s)
+ except ValueError:
+ return s
+
+ return [tryint(c) for c in re.split(r"(\d+)", s)]
+
+def human_sorted(strings):
+ """Sort the given iterable of strings the way that humans expect.
+
+ Numeric components in the strings are sorted as numbers.
+
+ Returns the sorted list.
+
+ """
+ return sorted(strings, key=human_key)
+
+def human_sorted_items(items, reverse=False):
+ """Sort the (string, value) items the way humans expect.
+
+ Returns the sorted list of items.
+ """
+ return sorted(items, key=lambda pair: (human_key(pair[0]), pair[1]), reverse=reverse)