Skip to content

Commit 768fa14

Browse files
authored
bpo-42772: Step argument ignored when stop is None. (GH-24018)
1 parent 607501a commit 768fa14

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

Lib/random.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@
9696
SG_MAGICCONST = 1.0 + _log(4.5)
9797
BPF = 53 # Number of bits in a float
9898
RECIP_BPF = 2 ** -BPF
99+
_ONE = 1
99100

100101

101102
class Random(_random.Random):
@@ -288,7 +289,7 @@ def randbytes(self, n):
288289

289290
## -------------------- integer methods -------------------
290291

291-
def randrange(self, start, stop=None, step=1):
292+
def randrange(self, start, stop=None, step=_ONE):
292293
"""Choose a random item from range(start, stop[, step]).
293294
294295
This fixes the problem with randint() which includes the
@@ -311,7 +312,12 @@ def randrange(self, start, stop=None, step=1):
311312
_warn('randrange() will raise TypeError in the future',
312313
DeprecationWarning, 2)
313314
raise ValueError("non-integer arg 1 for randrange()")
315+
314316
if stop is None:
317+
# We don't check for "step != 1" because it hasn't been
318+
# type checked and converted to an integer yet.
319+
if step is not _ONE:
320+
raise TypeError('Missing a non-None stop argument')
315321
if istart > 0:
316322
return self._randbelow(istart)
317323
raise ValueError("empty range for randrange()")

Lib/test/test_random.py

+8
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,14 @@ def test_randrange_argument_handling(self):
562562
with self.assertRaises(ValueError):
563563
randrange(10, 20, 1.5)
564564

565+
def test_randrange_step(self):
566+
# bpo-42772: When stop is None, the step argument was being ignored.
567+
randrange = self.gen.randrange
568+
with self.assertRaises(TypeError):
569+
randrange(1000, step=100)
570+
with self.assertRaises(TypeError):
571+
randrange(1000, None, step=100)
572+
565573
def test_randbelow_logic(self, _log=log, int=int):
566574
# check bitcount transition points: 2**i and 2**(i+1)-1
567575
# show that: k = int(1.001 + _log(n, 2))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
randrange() now raises a TypeError when step is specified without a stop
2+
argument. Formerly, it silently ignored the step argument.

0 commit comments

Comments
 (0)