On this page
functools.cmp_to_key
Prev: functools.cached_property | Up: functools | Next: functools.lru_cache
Rel: functools.cache, functools.cached_property, functools.lru_cache, functools.partial
Ref: docs.python.org — functools.cmp_to_key
Tags: #public #python3 #stdlib #functools
Import
import functools
from functools import cmp_to_key
Signature & Overview
functools.cmp_to_key(mycmp)
Convert a cmp= function into a key= function.
Usage
from functools import cmp_to_key
def compare_versions(a: str, b: str) -> int:
pa, pb = [int(x) for x in a.split(".")], [int(x) for x in b.split(".")]
return (pa > pb) - (pa < pb)
assert sorted(["1.10", "1.2", "1.1"], key=cmp_to_key(compare_versions)) == ["1.1", "1.2", "1.10"]
Gotchas
- Return negative,
0, or positive: The comparator must return< 0fora < b,0fora == b, and> 0fora > b(not abool). - Prefer a direct
key=function when possible: A plainkey=lambda s: [int(x) for x in s.split(".")]is faster and simpler whenever a comparison can be expressed as a sort key.
REPL Inspect
from functools import cmp_to_key
help(cmp_to_key)
Linked from
- tuts/python3/stdlib_module/functools
- tuts/python3/stdlib_module/functools/cache
- tuts/python3/stdlib_module/functools/cached_property
- tuts/python3/stdlib_module/functools/lru_cache
- tuts/python3/stdlib_module/functools/partial
- tuts/python3/stdlib_module/functools/partialmethod
- tuts/python3/stdlib_module/functools/reduce
- tuts/python3/stdlib_module/functools/singledispatch
- tuts/python3/stdlib_module/functools/singledispatchmethod
- tuts/python3/stdlib_module/functools/total_ordering
- tuts/python3/stdlib_module/functools/update_wrapper
- tuts/python3/stdlib_module/functools/wraps
Related notes
- tuts/python3/stdlib_module/functools/cache Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/cached_property Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/lru_cache Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/partial Linked here; links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/functools/partialmethod links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/reduce links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/singledispatch links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/singledispatchmethod links to this page; shared tags: #functools, #stdlib
- tuts/python3/stdlib_module/functools/total_ordering links to this page; shared tags: #functools, #stdlib