|
50 | 50 | # Adrian Baddeley. Adapted by Raymond Hettinger for use with |
51 | 51 | # the Mersenne Twister and os.urandom() core generators. |
52 | 52 |
|
53 | | -from warnings import warn as _warn |
54 | 53 | from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil |
55 | 54 | from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin |
56 | 55 | from math import tau as TWOPI, floor as _floor, isfinite as _isfinite |
|
63 | 62 | import os as _os |
64 | 63 | import _random |
65 | 64 |
|
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 | | - |
73 | 65 | __all__ = [ |
74 | 66 | "Random", |
75 | 67 | "SystemRandom", |
|
105 | 97 | BPF = 53 # Number of bits in a float |
106 | 98 | RECIP_BPF = 2 ** -BPF |
107 | 99 | _ONE = 1 |
| 100 | +_sha512 = None |
108 | 101 |
|
109 | 102 |
|
110 | 103 | class Random(_random.Random): |
@@ -159,6 +152,16 @@ def seed(self, a=None, version=2): |
159 | 152 | a = -2 if x == -1 else x |
160 | 153 |
|
161 | 154 | elif version == 2 and isinstance(a, (str, bytes, bytearray)): |
| 155 | + global _sha512 |
| 156 | + if _sha512 is None: |
| 157 | + try: |
| 158 | + # hashlib is pretty heavy to load, try lean internal |
| 159 | + # module first |
| 160 | + from _sha2 import sha512 as _sha512 |
| 161 | + except ImportError: |
| 162 | + # fallback to official implementation |
| 163 | + from hashlib import sha512 as _sha512 |
| 164 | + |
162 | 165 | if isinstance(a, str): |
163 | 166 | a = a.encode() |
164 | 167 | a = int.from_bytes(a + _sha512(a).digest()) |
@@ -257,9 +260,10 @@ def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF): |
257 | 260 |
|
258 | 261 | random = self.random |
259 | 262 | 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.") |
| 263 | + from warnings import warn |
| 264 | + warn("Underlying random() generator does not supply \n" |
| 265 | + "enough bits to choose from a population range this large.\n" |
| 266 | + "To remove the range limitation, add a getrandbits() method.") |
263 | 267 | return _floor(random() * n) |
264 | 268 | rem = maxsize % n |
265 | 269 | limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0 |
|
0 commit comments