Skip to content

Commit befc956

Browse files
[3.6] bpo-31478: Fix an assertion failure in random.seed() in case a seed has a bad __abs__() method. (GH-3596) (#3794)
(cherry picked from commit d780b2d)
1 parent 68b131d commit befc956

3 files changed

Lines changed: 18 additions & 2 deletions

File tree

Lib/test/test_random.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,17 @@ def test_bug_27706(self):
423423
['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
424424
'0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
425425

426+
def test_bug_31478(self):
427+
# There shouldn't be an assertion failure in _random.Random.seed() in
428+
# case the argument has a bad __abs__() method.
429+
class BadInt(int):
430+
def __abs__(self):
431+
return None
432+
try:
433+
self.gen.seed(BadInt())
434+
except TypeError:
435+
pass
436+
426437
def test_bug_31482(self):
427438
# Verify that version 1 seeds are unaffected by hash randomization
428439
# when the seeds are expressed as bytes rather than strings.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix an assertion failure in `_random.Random.seed()` in case the argument has a
2+
bad ``__abs__()`` method. Patch by Oren Milman.

Modules/_randommodule.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -259,8 +259,11 @@ random_seed(RandomObject *self, PyObject *args)
259259
* So: if the arg is a PyLong, use its absolute value.
260260
* Otherwise use its hash value, cast to unsigned.
261261
*/
262-
if (PyLong_Check(arg))
263-
n = PyNumber_Absolute(arg);
262+
if (PyLong_Check(arg)) {
263+
/* Calling int.__abs__() prevents calling arg.__abs__(), which might
264+
return an invalid value. See issue #31478. */
265+
n = PyLong_Type.tp_as_number->nb_absolute(arg);
266+
}
264267
else {
265268
Py_hash_t hash = PyObject_Hash(arg);
266269
if (hash == -1)

0 commit comments

Comments
 (0)