Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 112835c

Browse files
committed
Merge
2 parents 898ac56 + c7bab7c commit 112835c

3 files changed

Lines changed: 30 additions & 0 deletions

File tree

Lib/random.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,13 @@ def seed(self, a=None, version=2):
112112
import time
113113
a = int(time.time() * 256) # use fractional seconds
114114

115+
if version == 1 and isinstance(a, (str, bytes)):
116+
x = ord(a[0]) << 7 if a else 0
117+
for c in a:
118+
x = ((1000003 * x) ^ ord(c)) & 0xFFFFFFFFFFFFFFFF
119+
x ^= len(a)
120+
a = -2 if x == -1 else x
121+
115122
if version == 2:
116123
if isinstance(a, (str, bytes, bytearray)):
117124
if isinstance(a, str):

Lib/test/test_random.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,24 @@ def test_guaranteed_stable(self):
326326
['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
327327
'0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
328328

329+
def test_bug_27706(self):
330+
# Verify that version 1 seeds are unaffected by hash randomization
331+
332+
self.gen.seed('nofar', version=1) # hash('nofar') == 5990528763808513177
333+
self.assertEqual([self.gen.random().hex() for i in range(4)],
334+
['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
335+
'0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
336+
337+
self.gen.seed('rachel', version=1) # hash('rachel') == -9091735575445484789
338+
self.assertEqual([self.gen.random().hex() for i in range(4)],
339+
['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
340+
'0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
341+
342+
self.gen.seed('', version=1) # hash('') == 0
343+
self.assertEqual([self.gen.random().hex() for i in range(4)],
344+
['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
345+
'0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
346+
329347
def test_setstate_first_arg(self):
330348
self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
331349

Misc/NEWS

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ Library
7272

7373
- Issue #19884: Avoid spurious output on OS X with Gnu Readline.
7474

75+
- Issue #27706: Restore deterministic behavior of random.Random().seed()
76+
for string seeds using seeding version 1. Allows sequences of calls
77+
to random() to exactly match those obtained in Python 2.
78+
Patch by Nofar Schnider.
79+
7580
- Issue #10513: Fix a regression in Connection.commit(). Statements should
7681
not be reset after a commit.
7782

0 commit comments

Comments
 (0)