Skip to content

Instantly share code, notes, and snippets.

@jorenham
Last active October 18, 2021 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorenham/2db1ada000c07a6960f8a697cc551b33 to your computer and use it in GitHub Desktop.
Save jorenham/2db1ada000c07a6960f8a697cc551b33 to your computer and use it in GitHub Desktop.
Python cmp function, type annotated, and correctly handled nan's
from typing import Optional, TYPE_CHECKING
if TYPE_CHECKING:
from _typeshed import SupportsLessThan
def cmp(a: 'SupportsLessThan', b: 'SupportsLessThan') -> Optional[int]:
"""Return 1 if a > b, 0 if a == b, -1 if a < b, otherwise None.
>>> cmp(42, 69), cmp(666, 666), cmp(69, 42), cmp(0, float('nan'))
(1, 0, -1, None)
>>> cmp('42', '69'), cmp([666], [666]), cmp({0, 1}, {1}), cmp({0}, {1})
(1, 0, -1, None)
"""
return (a < b) - (a > b) or +(a != b) and None
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment