Last active
October 18, 2021 13:02
-
-
Save jorenham/2db1ada000c07a6960f8a697cc551b33 to your computer and use it in GitHub Desktop.
Python cmp function, type annotated, and correctly handled nan's
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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