On this page
  1. functools.cmp_to_key
  2. Import
  3. Signature & Overview
  4. Usage
  5. Gotchas
  6. REPL Inspect

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

REPL Inspect

from functools import cmp_to_key
help(cmp_to_key)

Linked from

Related notes