[2.7] bpo-31478: Prevent unwanted behavior in _random.Random.seed() in case the arg has a bad __abs__() method (GH-3596) (#3845)

diff --git a/Modules/_randommodule.c b/Modules/_randommodule.c
index 852b810..2e49db6 100644
--- a/Modules/_randommodule.c
+++ b/Modules/_randommodule.c
@@ -230,9 +230,15 @@
     }
     /* If the arg is an int or long, use its absolute value; else use
      * the absolute value of its hash code.
+     * Calling int.__abs__() or long.__abs__() prevents calling arg.__abs__(),
+     * which might return an invalid value. See issue #31478.
      */
-    if (PyInt_Check(arg) || PyLong_Check(arg))
-        n = PyNumber_Absolute(arg);
+    if (PyInt_Check(arg)) {
+        n = PyInt_Type.tp_as_number->nb_absolute(arg);
+    }
+    else if (PyLong_Check(arg)) {
+        n = PyLong_Type.tp_as_number->nb_absolute(arg);
+    }
     else {
         long hash = PyObject_Hash(arg);
         if (hash == -1)