Skip to content

Commit f19af2f

Browse files
committed
gh-111881: Use lazy imports in the random module
The random module now imports the _sha2 module lazily in the Random.seed() method for str, bytes and bytearray seeds. It also imports lazily the warnings module in the _randbelow() method for classes without getrandbits(). Lazy import makes Python startup faster and reduces the number of imported modules at startup.
1 parent 0c42f73 commit f19af2f

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

Lib/random.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@
5050
# Adrian Baddeley. Adapted by Raymond Hettinger for use with
5151
# the Mersenne Twister and os.urandom() core generators.
5252

53-
from warnings import warn as _warn
5453
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
5554
from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
5655
from math import tau as TWOPI, floor as _floor, isfinite as _isfinite
@@ -63,13 +62,6 @@
6362
import os as _os
6463
import _random
6564

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-
7365
__all__ = [
7466
"Random",
7567
"SystemRandom",
@@ -159,6 +151,14 @@ def seed(self, a=None, version=2):
159151
a = -2 if x == -1 else x
160152

161153
elif version == 2 and isinstance(a, (str, bytes, bytearray)):
154+
try:
155+
# hashlib is pretty heavy to load, try lean internal
156+
# module first
157+
from _sha2 import sha512 as _sha512
158+
except ImportError:
159+
# fallback to official implementation
160+
from hashlib import sha512 as _sha512
161+
162162
if isinstance(a, str):
163163
a = a.encode()
164164
a = int.from_bytes(a + _sha512(a).digest())
@@ -257,9 +257,10 @@ def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF):
257257

258258
random = self.random
259259
if n >= maxsize:
260-
_warn("Underlying random() generator does not supply \n"
261-
"enough bits to choose from a population range this large.\n"
262-
"To remove the range limitation, add a getrandbits() method.")
260+
from warnings import warn
261+
warn("Underlying random() generator does not supply \n"
262+
"enough bits to choose from a population range this large.\n"
263+
"To remove the range limitation, add a getrandbits() method.")
263264
return _floor(random() * n)
264265
rem = maxsize % n
265266
limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0

0 commit comments

Comments
 (0)