[Python-ideas] Pre-PEP Adding A Secrets Module To The Standard Library

Andrew Barnert abarnert at yahoo.com
Mon Sep 21 21:21:49 CEST 2015


On Sep 21, 2015, at 10:51, Tim Peters <tim.peters at gmail.com> wrote:

>> When would somebody use randbelow(n) rather than randrange(n)?
> 
> For the same reason they'd use randbits(n) instead of randrange(1 <<
> n) ;-)  That is, familiarity and obviousness.  randrange() has a
> complicated signature, with 1 to 3 arguments, and endlessly surprises
> newbies who _expect_, e.g., randrange(3) to return 3 at times.  That's
> why randint() was created.

Anyone who gets confused by randrange(3) also gets confused by range(3), and they have to learn pretty quickly.

Also, randint wasn't created to allow people to put off learning that fact. It was created before randrange, because Adrian Baddeley didn't realize that Python consistently used half-open ranges, and Guido didn't notice. After 1.5 was out and someone complained that choice(range(...)) was inefficient, Guido added randrange. See the commit comment (61464037da53) which says "This addresses the problem that randint() was accidentally defined as taking an inclusive range (how unpythonic)".Also, some guy named Tim Peters convinced Guido that randint(0, 2.5) was surprisingly broken, so if he wasn't going to remove it he should reimplement it as randrange(a, b+1), which would give a clear error message. Later still (3.0), there was another discussion on removing randint, but the decision was to keep it as a "legacy alias", and change the docs to reflect that.

I suppose randbelow could be implemented as an alias to randrange(a), or it could copy and paste the same type checks as randrange, but honestly, I don't think anyone needs it.


More information about the Python-ideas mailing list