Initialize internal state from a seed. The only supported seed types are None, int, float, str, bytes, and bytearray. None or no argument seeds from current time or from an operating system specific randomness source if available. If *a* is an int, all bits
(self, a=None, version=2)
| 126 | self.gauss_next = None |
| 127 | |
| 128 | def seed(self, a=None, version=2): |
| 129 | """Initialize internal state from a seed. |
| 130 | |
| 131 | The only supported seed types are None, int, float, |
| 132 | str, bytes, and bytearray. |
| 133 | |
| 134 | None or no argument seeds from current time or from an operating |
| 135 | system specific randomness source if available. |
| 136 | |
| 137 | If *a* is an int, all bits are used. |
| 138 | |
| 139 | For version 2 (the default), all of the bits are used if *a* is a str, |
| 140 | bytes, or bytearray. For version 1 (provided for reproducing random |
| 141 | sequences from older versions of Python), the algorithm for str and |
| 142 | bytes generates a narrower range of seeds. |
| 143 | |
| 144 | """ |
| 145 | |
| 146 | if version == 1 and isinstance(a, (str, bytes)): |
| 147 | a = a.decode('latin-1') if isinstance(a, bytes) else a |
| 148 | x = ord(a[0]) << 7 if a else 0 |
| 149 | for c in map(ord, a): |
| 150 | x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF |
| 151 | x ^= len(a) |
| 152 | a = -2 if x == -1 else x |
| 153 | |
| 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 | |
| 165 | if isinstance(a, str): |
| 166 | a = a.encode() |
| 167 | a = int.from_bytes(a + _sha512(a).digest()) |
| 168 | |
| 169 | elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)): |
| 170 | raise TypeError('The only supported seed types are:\n' |
| 171 | 'None, int, float, str, bytes, and bytearray.') |
| 172 | |
| 173 | super().seed(a) |
| 174 | self.gauss_next = None |
| 175 | |
| 176 | def getstate(self): |
| 177 | """Return internal state; can be passed to setstate() later.""" |