Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,22 @@ def test_randbelow_logic(self, _log=log, int=int):
class MersenneTwister_TestBasicOps(TestBasicOps):
gen = random.Random()

@test_support.cpython_only
def test_bug_31478(self):
# _random.Random.seed() should ignore the __abs__() method of a
# long/int subclass argument.
class BadInt(int):
def __abs__(self):
1/0
class BadLong(long):
def __abs__(self):
1/0
self.gen.seed(42)
expected_value = self.gen.random()
for seed_arg in [42L, BadInt(42), BadLong(42)]:
self.gen.seed(seed_arg)
self.assertEqual(self.gen.random(), expected_value)

def test_setstate_first_arg(self):
self.assertRaises(ValueError, self.gen.setstate, (1, None, None))

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Prevent unwanted behavior in `_random.Random.seed()` in case the argument
has a bad ``__abs__()`` method. Patch by Oren Milman.
10 changes: 8 additions & 2 deletions Modules/_randommodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,15 @@ random_seed(RandomObject *self, PyObject *args)
}
/* 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)
Expand Down