Skip to content

Commit 969e5c8

Browse files
committed
gh-111881: Import _sha2 lazily in random
The random module now imports the _sha2 module laziliy in Random.seed() method for str, bytes and bytearray seeds. Lazy import makes Python startup faster and reduce the number of imported modules at startup.
1 parent cc18b88 commit 969e5c8

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

Lib/random.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -63,13 +63,6 @@
6363
import os as _os
6464
import _random
6565

66-
try:
67-
# hashlib is pretty heavy to load, try lean internal module first
68-
from _sha2 import sha512 as _sha512
69-
except ImportError:
70-
# fallback to official implementation
71-
from hashlib import sha512 as _sha512
72-
7366
__all__ = [
7467
"Random",
7568
"SystemRandom",
@@ -159,6 +152,14 @@ def seed(self, a=None, version=2):
159152
a = -2 if x == -1 else x
160153

161154
elif version == 2 and isinstance(a, (str, bytes, bytearray)):
155+
try:
156+
# hashlib is pretty heavy to load, try lean internal
157+
# module first
158+
from _sha2 import sha512 as _sha512
159+
except ImportError:
160+
# fallback to official implementation
161+
from hashlib import sha512 as _sha512
162+
162163
if isinstance(a, str):
163164
a = a.encode()
164165
a = int.from_bytes(a + _sha512(a).digest())

0 commit comments

Comments
 (0)