[New-bugs-announce] [issue42559] random.getrandbits: Should it be explicit that it returns unsigned/non-negative integer?
report at bugs.python.org
Thu Dec 3 12:53:56 EST 2020
New submission from Paul Sokolovsky <pfalcon at users.sourceforge.net>:
Current docs for random.getrandbits() ( https://docs.python.org/3/library/random.html#random.getrandbits ) read (3.9.1rc1 at the top of the page):
Returns a Python integer with k random bits. This method is supplied with the MersenneTwister generator and some other generators may also provide it as an optional part of the API. When available, getrandbits() enables randrange() to handle arbitrarily large ranges.
So, based that it talks about "bits", it's easy to imagine that the result is unsigned. But it's interesting that it mentions "a Python integer", not even just "integer". And Python integers are known to be signed.
So I'd say, there's enough of ambiguity in there, and would be nice to explicitly specify that it's "unsigned (non-negative) Python integer".
If there's interest for the background of concern, some implementations may have "small" and "large" integers underlyingly (which used to be exposed at the user-level in Python2). "Small" integers would be cheaper, but of course, they would be signed. So, at certain value of getrandbits() parameter, there may be a temptation to use up a sign bit of a small integer, instead of going straight to allocating expensive large integer. It should be clear this is NOT a valid "optimization", and result should be always non-negative.
title: random.getrandbits: Should it be explicit that it returns unsigned/non-negative integer?
versions: Python 3.9
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce