[3.9] bpo-41052: Opt out serialization/deserialization for _random.Random (GH-21002). (GH-21030)

(cherry picked from commit 6989af0bc7)

Co-authored-by: Dong-hee Na <donghee.na92@gmail.com>
This commit is contained in:
Dong-hee Na 2020-06-21 19:33:06 +09:00 committed by GitHub
parent 71bb921829
commit 814b07bf81
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 47 additions and 1 deletions

View file

@ -5,6 +5,8 @@ import os
import time
import pickle
import warnings
import test.support
from functools import partial
from math import log, exp, pi, fsum, sin, factorial
from test import support
@ -372,6 +374,14 @@ class TestBasicOps:
restoredseq = [newgen.random() for i in range(10)]
self.assertEqual(origseq, restoredseq)
@test.support.cpython_only
def test_bug_41052(self):
# _random.Random should not be allowed to serialization
import _random
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
r = _random.Random()
self.assertRaises(TypeError, pickle.dumps, r, proto)
def test_bug_1727780(self):
# verify that version-2-pickles can be loaded
# fine, whether they are created on 32-bit or 64-bit

View file

@ -0,0 +1 @@
Opt out serialization/deserialization for _random.Random

View file

@ -536,12 +536,30 @@ random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return (PyObject *)self;
}
/*[clinic input]
_random.Random.__reduce__
[clinic start generated code]*/
static PyObject *
_random_Random___reduce___impl(RandomObject *self)
/*[clinic end generated code: output=ddea0dcdb60ffd6d input=bd38ec35fd157e0f]*/
{
PyErr_Format(PyExc_TypeError,
"cannot pickle %s object",
Py_TYPE(self)->tp_name);
return NULL;
}
static PyMethodDef random_methods[] = {
_RANDOM_RANDOM_RANDOM_METHODDEF
_RANDOM_RANDOM_SEED_METHODDEF
_RANDOM_RANDOM_GETSTATE_METHODDEF
_RANDOM_RANDOM_SETSTATE_METHODDEF
_RANDOM_RANDOM_GETRANDBITS_METHODDEF
_RANDOM_RANDOM___REDUCE___METHODDEF
{NULL, NULL} /* sentinel */
};

View file

@ -114,4 +114,21 @@ _random_Random_getrandbits(RandomObject *self, PyObject *arg)
exit:
return return_value;
}
/*[clinic end generated code: output=a7feb0c9c8d1b627 input=a9049054013a1b77]*/
PyDoc_STRVAR(_random_Random___reduce____doc__,
"__reduce__($self, /)\n"
"--\n"
"\n");
#define _RANDOM_RANDOM___REDUCE___METHODDEF \
{"__reduce__", (PyCFunction)_random_Random___reduce__, METH_NOARGS, _random_Random___reduce____doc__},
static PyObject *
_random_Random___reduce___impl(RandomObject *self);
static PyObject *
_random_Random___reduce__(RandomObject *self, PyObject *Py_UNUSED(ignored))
{
return _random_Random___reduce___impl(self);
}
/*[clinic end generated code: output=d8a99be3f1192219 input=a9049054013a1b77]*/