Choose a random item from range(stop) or range(start, stop[, step]). Roughly equivalent to ``choice(range(start, stop, step))`` but supports arbitrarily large ranges and is optimized for common cases.
(self, start, stop=None, step=_ONE)
| 292 | ## -------------------- integer methods ------------------- |
| 293 | |
| 294 | def randrange(self, start, stop=None, step=_ONE): |
| 295 | """Choose a random item from range(stop) or range(start, stop[, step]). |
| 296 | |
| 297 | Roughly equivalent to ``choice(range(start, stop, step))`` but |
| 298 | supports arbitrarily large ranges and is optimized for common cases. |
| 299 | |
| 300 | """ |
| 301 | |
| 302 | # This code is a bit messy to make it fast for the |
| 303 | # common case while still doing adequate error checking. |
| 304 | istart = _index(start) |
| 305 | if stop is None: |
| 306 | # We don't check for "step != 1" because it hasn't been |
| 307 | # type checked and converted to an integer yet. |
| 308 | if step is not _ONE: |
| 309 | raise TypeError("Missing a non-None stop argument") |
| 310 | if istart > 0: |
| 311 | return self._randbelow(istart) |
| 312 | raise ValueError("empty range for randrange()") |
| 313 | |
| 314 | # Stop argument supplied. |
| 315 | istop = _index(stop) |
| 316 | width = istop - istart |
| 317 | istep = _index(step) |
| 318 | # Fast path. |
| 319 | if istep == 1: |
| 320 | if width > 0: |
| 321 | return istart + self._randbelow(width) |
| 322 | raise ValueError(f"empty range in randrange({start}, {stop})") |
| 323 | |
| 324 | # Non-unit step argument supplied. |
| 325 | if istep > 0: |
| 326 | n = (width + istep - 1) // istep |
| 327 | elif istep < 0: |
| 328 | n = (width + istep + 1) // istep |
| 329 | else: |
| 330 | raise ValueError("zero step for randrange()") |
| 331 | if n <= 0: |
| 332 | raise ValueError(f"empty range in randrange({start}, {stop}, {step})") |
| 333 | return istart + istep * self._randbelow(n) |
| 334 | |
| 335 | def randint(self, a, b): |
| 336 | """Return random integer in range [a, b], including both end points. |