Skip to content

Commit 6989af0

Browse files
authored
bpo-41052: Opt out serialization/deserialization for _random.Random (GH-21002)
1 parent f9bab74 commit 6989af0

File tree

4 files changed

+47
-1
lines changed

4 files changed

+47
-1
lines changed

Lib/test/test_random.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import time
66
import pickle
77
import warnings
8+
import test.support
9+
810
from functools import partial
911
from math import log, exp, pi, fsum, sin, factorial
1012
from test import support
@@ -372,6 +374,14 @@ def test_pickling(self):
372374
restoredseq = [newgen.random() for i in range(10)]
373375
self.assertEqual(origseq, restoredseq)
374376

377+
@test.support.cpython_only
378+
def test_bug_41052(self):
379+
# _random.Random should not be allowed to serialization
380+
import _random
381+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
382+
r = _random.Random()
383+
self.assertRaises(TypeError, pickle.dumps, r, proto)
384+
375385
def test_bug_1727780(self):
376386
# verify that version-2-pickles can be loaded
377387
# fine, whether they are created on 32-bit or 64-bit
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Opt out serialization/deserialization for _random.Random

Modules/_randommodule.c

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,12 +535,30 @@ random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
535535
return (PyObject *)self;
536536
}
537537

538+
539+
/*[clinic input]
540+
541+
_random.Random.__reduce__
542+
543+
[clinic start generated code]*/
544+
545+
static PyObject *
546+
_random_Random___reduce___impl(RandomObject *self)
547+
/*[clinic end generated code: output=ddea0dcdb60ffd6d input=bd38ec35fd157e0f]*/
548+
{
549+
PyErr_Format(PyExc_TypeError,
550+
"cannot pickle %s object",
551+
Py_TYPE(self)->tp_name);
552+
return NULL;
553+
}
554+
538555
static PyMethodDef random_methods[] = {
539556
_RANDOM_RANDOM_RANDOM_METHODDEF
540557
_RANDOM_RANDOM_SEED_METHODDEF
541558
_RANDOM_RANDOM_GETSTATE_METHODDEF
542559
_RANDOM_RANDOM_SETSTATE_METHODDEF
543560
_RANDOM_RANDOM_GETRANDBITS_METHODDEF
561+
_RANDOM_RANDOM___REDUCE___METHODDEF
544562
{NULL, NULL} /* sentinel */
545563
};
546564

Modules/clinic/_randommodule.c.h

Lines changed: 18 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)