]> git.ipfire.org Git - thirdparty/samba.git/commitdiff
py/common: add cmp_with_nones() helper function
authorDouglas Bagnall <douglas.bagnall@catalyst.net.nz>
Wed, 16 Jul 2025 23:42:54 +0000 (11:42 +1200)
committerDouglas Bagnall <dbagnall@samba.org>
Thu, 7 Aug 2025 23:28:33 +0000 (23:28 +0000)
Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
Reviewed-by: Gary Lockyer <gary@catalyst.net.nz>
python/samba/common.py
python/samba/tests/common.py

index f11cf383807762bb005b1fee6d98a00cf1259989..a76110bc68044f63bddfce4679ccf79a72565344 100644 (file)
@@ -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
 
index c767d2522f7c1992e463b253c7e7b8562d0891c4..7dd32efb90b92b8df25f86a18a1740134c1a33c1 100644 (file)
@@ -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)