@@ -167,15 +167,11 @@ def seed(self, a=None, version=2):
167
167
elif version == 2 and isinstance (a , (str , bytes , bytearray )):
168
168
if isinstance (a , str ):
169
169
a = a .encode ()
170
- a = int .from_bytes (a + _sha512 (a ).digest (), 'big' )
170
+ a = int .from_bytes (a + _sha512 (a ).digest ())
171
171
172
172
elif not isinstance (a , (type (None ), int , float , str , bytes , bytearray )):
173
- _warn ('Seeding based on hashing is deprecated\n '
174
- 'since Python 3.9 and will be removed in a subsequent '
175
- 'version. The only \n '
176
- 'supported seed types are: None, '
177
- 'int, float, str, bytes, and bytearray.' ,
178
- DeprecationWarning , 2 )
173
+ raise TypeError ('The only supported seed types are: None,\n '
174
+ 'int, float, str, bytes, and bytearray.' )
179
175
180
176
super ().seed (a )
181
177
self .gauss_next = None
@@ -250,10 +246,8 @@ def __init_subclass__(cls, /, **kwargs):
250
246
break
251
247
252
248
def _randbelow_with_getrandbits (self , n ):
253
- "Return a random int in the range [0,n). Returns 0 if n== 0."
249
+ "Return a random int in the range [0,n). Defined for n > 0."
254
250
255
- if not n :
256
- return 0
257
251
getrandbits = self .getrandbits
258
252
k = n .bit_length () # don't use (n-1) here because n can be 1
259
253
r = getrandbits (k ) # 0 <= r < 2**k
@@ -262,7 +256,7 @@ def _randbelow_with_getrandbits(self, n):
262
256
return r
263
257
264
258
def _randbelow_without_getrandbits (self , n , maxsize = 1 << BPF ):
265
- """Return a random int in the range [0,n). Returns 0 if n== 0.
259
+ """Return a random int in the range [0,n). Defined for n > 0.
266
260
267
261
The implementation does not use getrandbits, but only random.
268
262
"""
@@ -273,8 +267,6 @@ def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF):
273
267
"enough bits to choose from a population range this large.\n "
274
268
"To remove the range limitation, add a getrandbits() method." )
275
269
return _floor (random () * n )
276
- if n == 0 :
277
- return 0
278
270
rem = maxsize % n
279
271
limit = (maxsize - rem ) / maxsize # int(limit * maxsize) % n == 0
280
272
r = random ()
@@ -303,10 +295,10 @@ def randbytes(self, n):
303
295
## -------------------- integer methods -------------------
304
296
305
297
def randrange (self , start , stop = None , step = _ONE ):
306
- """Choose a random item from range(start, stop[, step]).
298
+ """Choose a random item from range(stop) or range( start, stop[, step]).
307
299
308
- This fixes the problem with randint() which includes the
309
- endpoint; in Python this is usually not what you want .
300
+ Roughly equivalent to ``choice(range(start, stop, step))`` but
301
+ supports arbitrarily large ranges and is optimized for common cases .
310
302
311
303
"""
312
304
@@ -387,37 +379,24 @@ def randint(self, a, b):
387
379
388
380
def choice (self , seq ):
389
381
"""Choose a random element from a non-empty sequence."""
390
- # raises IndexError if seq is empty
391
- return seq [self ._randbelow (len (seq ))]
392
-
393
- def shuffle (self , x , random = None ):
394
- """Shuffle list x in place, and return None.
395
382
396
- Optional argument random is a 0-argument function returning a
397
- random float in [0.0, 1.0); if it is the default None, the
398
- standard random.random will be used.
383
+ # As an accommodation for NumPy, we don't use "if not seq"
384
+ # because bool(numpy.array()) raises a ValueError.
385
+ if not len (seq ):
386
+ raise IndexError ('Cannot choose from an empty sequence' )
387
+ return seq [self ._randbelow (len (seq ))]
399
388
400
- """
389
+ def shuffle (self , x ):
390
+ """Shuffle list x in place, and return None."""
401
391
402
- if random is None :
403
- randbelow = self ._randbelow
404
- for i in reversed (range (1 , len (x ))):
405
- # pick an element in x[:i+1] with which to exchange x[i]
406
- j = randbelow (i + 1 )
407
- x [i ], x [j ] = x [j ], x [i ]
408
- else :
409
- _warn ('The *random* parameter to shuffle() has been deprecated\n '
410
- 'since Python 3.9 and will be removed in a subsequent '
411
- 'version.' ,
412
- DeprecationWarning , 2 )
413
- floor = _floor
414
- for i in reversed (range (1 , len (x ))):
415
- # pick an element in x[:i+1] with which to exchange x[i]
416
- j = floor (random () * (i + 1 ))
417
- x [i ], x [j ] = x [j ], x [i ]
392
+ randbelow = self ._randbelow
393
+ for i in reversed (range (1 , len (x ))):
394
+ # pick an element in x[:i+1] with which to exchange x[i]
395
+ j = randbelow (i + 1 )
396
+ x [i ], x [j ] = x [j ], x [i ]
418
397
419
398
def sample (self , population , k , * , counts = None ):
420
- """Chooses k unique random elements from a population sequence or set .
399
+ """Chooses k unique random elements from a population sequence.
421
400
422
401
Returns a new list containing elements from the population while
423
402
leaving the original population unchanged. The resulting list is
@@ -470,13 +449,8 @@ def sample(self, population, k, *, counts=None):
470
449
# causing them to eat more entropy than necessary.
471
450
472
451
if not isinstance (population , _Sequence ):
473
- if isinstance (population , _Set ):
474
- _warn ('Sampling from a set deprecated\n '
475
- 'since Python 3.9 and will be removed in a subsequent version.' ,
476
- DeprecationWarning , 2 )
477
- population = tuple (population )
478
- else :
479
- raise TypeError ("Population must be a sequence. For dicts or sets, use sorted(d)." )
452
+ raise TypeError ("Population must be a sequence. "
453
+ "For dicts or sets, use sorted(d)." )
480
454
n = len (population )
481
455
if counts is not None :
482
456
cum_counts = list (_accumulate (counts ))
@@ -580,7 +554,7 @@ def triangular(self, low=0.0, high=1.0, mode=None):
580
554
low , high = high , low
581
555
return low + (high - low ) * _sqrt (u * c )
582
556
583
- def normalvariate (self , mu , sigma ):
557
+ def normalvariate (self , mu = 0.0 , sigma = 1.0 ):
584
558
"""Normal distribution.
585
559
586
560
mu is the mean, and sigma is the standard deviation.
@@ -601,7 +575,7 @@ def normalvariate(self, mu, sigma):
601
575
break
602
576
return mu + z * sigma
603
577
604
- def gauss (self , mu , sigma ):
578
+ def gauss (self , mu = 0.0 , sigma = 1.0 ):
605
579
"""Gaussian distribution.
606
580
607
581
mu is the mean, and sigma is the standard deviation. This is
@@ -833,15 +807,15 @@ class SystemRandom(Random):
833
807
"""
834
808
835
809
def random (self ):
836
- """Get the next random number in the range [ 0.0, 1.0) ."""
837
- return (int .from_bytes (_urandom (7 ), 'big' ) >> 3 ) * RECIP_BPF
810
+ """Get the next random number in the range 0.0 <= X < 1.0."""
811
+ return (int .from_bytes (_urandom (7 )) >> 3 ) * RECIP_BPF
838
812
839
813
def getrandbits (self , k ):
840
814
"""getrandbits(k) -> x. Generates an int with k random bits."""
841
815
if k < 0 :
842
816
raise ValueError ('number of bits must be non-negative' )
843
817
numbytes = (k + 7 ) // 8 # bits / 8 and rounded up
844
- x = int .from_bytes (_urandom (numbytes ), 'big' )
818
+ x = int .from_bytes (_urandom (numbytes ))
845
819
return x >> (numbytes * 8 - k ) # trim excess bits
846
820
847
821
def randbytes (self , n ):
0 commit comments