Skip to content

Commit d914596

Browse files
tiranrhettinger
authored andcommitted
bpo-36559: random module: optimize sha512 import (GH-12742)
The random module now prefers the lean internal _sha512 module over hashlib for seed(version=2) to optimize import time. Signed-off-by: Christian Heimes <[email protected]>
1 parent 6955d44 commit d914596

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

Lib/random.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,18 @@
4242
from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
4343
from os import urandom as _urandom
4444
from _collections_abc import Set as _Set, Sequence as _Sequence
45-
from hashlib import sha512 as _sha512
4645
from itertools import accumulate as _accumulate, repeat as _repeat
4746
from bisect import bisect as _bisect
4847
import os as _os
4948

49+
try:
50+
# hashlib is pretty heavy to load, try lean internal module first
51+
from _sha512 import sha512 as _sha512
52+
except ImportError:
53+
# fallback to official implementation
54+
from hashlib import sha512 as _sha512
55+
56+
5057
__all__ = ["Random","seed","random","uniform","randint","choice","sample",
5158
"randrange","shuffle","normalvariate","lognormvariate",
5259
"expovariate","vonmisesvariate","gammavariate","triangular",
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The random module now prefers the lean internal _sha512 module over hashlib
2+
for seed(version=2) to optimize import time.

0 commit comments

Comments
 (0)