From: Douglas Bagnall Date: Wed, 16 Jul 2025 23:42:54 +0000 (+1200) Subject: py/common: add cmp_with_nones() helper function X-Git-Url: http://git.ipfire.org/gitweb/gitweb.cgi?a=commitdiff_plain;h=e68bbd0afe602f6a70b1ba07fca47648239553df;p=thirdparty%2Fsamba.git py/common: add cmp_with_nones() helper function Signed-off-by: Douglas Bagnall Reviewed-by: Gary Lockyer --- diff --git a/python/samba/common.py b/python/samba/common.py index f11cf383807..a76110bc680 100644 --- a/python/samba/common.py +++ b/python/samba/common.py @@ -30,6 +30,23 @@ def cmp(x, y): return (x > y) - (x < y) +def cmp_with_nones(x, y): + """This is like cmp(), but will cope if a value is None. + + We sort Nones to the start. + """ + # avoids + # TypeError: '>' not supported between instances of 'NoneType' and 'int' + if x == y: + return 0 + if x is None: + return -1 + if y is None: + return 1 + + return (x > y) - (x < y) + + def confirm(msg, forced=False, allow_all=False): """confirm an action with the user diff --git a/python/samba/tests/common.py b/python/samba/tests/common.py index c767d2522f7..7dd32efb90b 100644 --- a/python/samba/tests/common.py +++ b/python/samba/tests/common.py @@ -19,7 +19,7 @@ import samba import samba.tests -from samba.common import normalise_int32 +from samba.common import normalise_int32, cmp_with_nones class CommonTests(samba.tests.TestCase): @@ -32,3 +32,17 @@ class CommonTests(samba.tests.TestCase): self.assertRaises(ValueError, normalise_int32, 1 << 32) self.assertRaises(ValueError, normalise_int32, 12345678901234567890) self.assertRaises(ValueError, normalise_int32, -1000000000000) + + def test_cmp_with_nones(self): + for pair, outcome in [ + ((0, 0), 0), + ((2, 0), 1), + ((1, 2), -1), + ((None, 2), -1), + ((None, None), 0), + ((-6, None), 1), + (('a', None), 1), + ((object(), None), 1), + ((None, 1.2), -1), + ]: + self.assertEqual(cmp_with_nones(*pair), outcome)