Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
SG_MAGICCONST = 1.0 + _log(4.5)
BPF = 53 # Number of bits in a float
RECIP_BPF = 2 ** -BPF
_ONE = 1


class Random(_random.Random):
Expand Down Expand Up @@ -288,7 +289,7 @@ def randbytes(self, n):

## -------------------- integer methods -------------------

def randrange(self, start, stop=None, step=1):
def randrange(self, start, stop=None, step=_ONE):
"""Choose a random item from range(start, stop[, step]).

This fixes the problem with randint() which includes the
Expand All @@ -311,7 +312,12 @@ def randrange(self, start, stop=None, step=1):
_warn('randrange() will raise TypeError in the future',
DeprecationWarning, 2)
raise ValueError("non-integer arg 1 for randrange()")

if stop is None:
# We don't check for "step != 1" because it hasn't been
# type checked and converted to an integer yet.
if step is not _ONE:
raise TypeError('Missing a non-None stop argument')
if istart > 0:
return self._randbelow(istart)
raise ValueError("empty range for randrange()")
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,14 @@ def test_randrange_argument_handling(self):
with self.assertRaises(ValueError):
randrange(10, 20, 1.5)

def test_randrange_step(self):
# bpo-42772: When stop is None, the step argument was being ignored.
randrange = self.gen.randrange
with self.assertRaises(TypeError):
randrange(1000, step=100)
with self.assertRaises(TypeError):
randrange(1000, None, step=100)

def test_randbelow_logic(self, _log=log, int=int):
# check bitcount transition points: 2**i and 2**(i+1)-1
# show that: k = int(1.001 + _log(n, 2))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
randrange() now raises a TypeError when step is specified without a stop
argument. Formerly, it silently ignored the step argument.