Description
Feature or enhancement
Support of the __index__()
method in getrandbits() and randbytes() is inconsistent.
Random.getrandbits()
supports__index__()
, butSystemRandom.getrandbits()
does not.SystemRandom.randbytes()
supports__index__()
, butRandom.randbytes()
does not.
For consistence, both classes should support it.
sample()
fails if its k
argument is not integer. k
should have __index__()
, but it also should support comparison with integers and multiplication by list and integer. It is easy to make it more general, and only require __index__()
. It will also produce more meaningful error.
binomialvariate()
seems "working" with non-integer n
argument, but the result is questionable. Passing non-integer value is most likely an error, and it would be better to detect it.
cc @rhettinger
Activity
rhettinger commentedon Jun 17, 2025
Personally, I don't think this is needed. It is just overhead that doesn't benefit real users.
In pure python code, we commonly do much less error checking on inputs than we do in C code.
serhiy-storchaka commentedon Jun 19, 2025
Yes, unfortunately it has a cost.
The worst case:
It is less for larger argument:
SystemRandom.getrandbits()
is so slow, that the difference is insignificant.For
binomialvariate()
, the effect is much weaker for n > 1.On other hand,
operator.index()
is already called multiple times forrandrange()
andrandint()
.