44
44
from _collections_abc import Set as _Set , Sequence as _Sequence
45
45
from itertools import accumulate as _accumulate , repeat as _repeat
46
46
from bisect import bisect as _bisect
47
+ from operator import index as _index
47
48
import os as _os
48
49
49
50
try :
@@ -208,7 +209,7 @@ def __reduce__(self):
208
209
209
210
## -------------------- integer methods -------------------
210
211
211
- def randrange (self , start , stop = None , step = 1 , _int = int ):
212
+ def randrange (self , start , stop = None , step = 1 , _index = _index ):
212
213
"""Choose a random item from range(start, stop[, step]).
213
214
214
215
This fixes the problem with randint() which includes the
@@ -218,39 +219,33 @@ def randrange(self, start, stop=None, step=1, _int=int):
218
219
219
220
# This code is a bit messy to make it fast for the
220
221
# common case while still doing adequate error checking.
221
- istart = _int (start )
222
- if istart != start :
223
- raise ValueError ("non-integer arg 1 for randrange()" )
222
+ start = _index (start )
224
223
if stop is None :
225
- if istart > 0 :
226
- return self ._randbelow (istart )
224
+ if start > 0 :
225
+ return self ._randbelow (start )
227
226
raise ValueError ("empty range for randrange()" )
228
227
229
228
# stop argument supplied.
230
- istop = _int (stop )
231
- if istop != stop :
232
- raise ValueError ("non-integer stop for randrange()" )
233
- width = istop - istart
229
+ stop = _index (stop )
230
+ width = stop - start
234
231
if step == 1 and width > 0 :
235
- return istart + self ._randbelow (width )
232
+ return start + self ._randbelow (width )
236
233
if step == 1 :
237
- raise ValueError ("empty range for randrange() (%d, %d, %d)" % (istart , istop , width ))
234
+ raise ValueError ("empty range for randrange() (%d, %d, %d)" % (start , stop , width ))
238
235
239
236
# Non-unit step argument supplied.
240
- istep = _int (step )
241
- if istep != step :
242
- raise ValueError ("non-integer step for randrange()" )
243
- if istep > 0 :
244
- n = (width + istep - 1 ) // istep
245
- elif istep < 0 :
246
- n = (width + istep + 1 ) // istep
237
+ step = _index (step )
238
+ if step > 0 :
239
+ n = (width + step - 1 ) // step
240
+ elif step < 0 :
241
+ n = (width + step + 1 ) // step
247
242
else :
248
243
raise ValueError ("zero step for randrange()" )
249
244
250
245
if n <= 0 :
251
246
raise ValueError ("empty range for randrange()" )
252
247
253
- return istart + istep * self ._randbelow (n )
248
+ return start + step * self ._randbelow (n )
254
249
255
250
def randint (self , a , b ):
256
251
"""Return random integer in range [a, b], including both end points.
0 commit comments