Skip to content

Commit d780b2d

Browse files
orenmnserhiy-storchaka
authored andcommitted
bpo-31478: Fix an assertion failure in random.seed() in case a seed has a bad __abs__() method. (#3596)
1 parent db50ba7 commit d780b2d

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

Lib/test/test_random.py

+11
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,17 @@ def test_bug_27706(self):
430430
['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
431431
'0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
432432

433+
def test_bug_31478(self):
434+
# There shouldn't be an assertion failure in _random.Random.seed() in
435+
# case the argument has a bad __abs__() method.
436+
class BadInt(int):
437+
def __abs__(self):
438+
return None
439+
try:
440+
self.gen.seed(BadInt())
441+
except TypeError:
442+
pass
443+
433444
def test_bug_31482(self):
434445
# Verify that version 1 seeds are unaffected by hash randomization
435446
# when the seeds are expressed as bytes rather than strings.
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

+5-2
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)