Python does not have a random.randbool
function, although it has randint
, randrange
and random
. If I wanted to use a randbool
function, nothing stops me from using the following code:
import random
random.randbool = lambda: random.random() >= 0.5
Is it recommended to do this? Is it 'pythonic'? Is it much slower? This definitely allows for ease of understanding in later code, since instead inlining random.random() >= 0.5
or random.choice([False, True])
could be more confusing.
The alternative is, of course, just using a regular function -
def randbool():
return random.random() >= 0.5
Which is better?
Edit: Some timeit
benchmarks:
> python -m timeit -s "import random" -s "def randbool():" -s " return random.random() >= 0.5" "randbool()
1000000 loops, best of 3: 0.275 usec per loop
> python -m timeit -s "import random" "random.random() >= 0.5"
10000000 loops, best of 3: 0.152 usec per loop
> python -m timeit -s "import random" -s "random.randbool = lambda: random.random() >= 0.5" "random.randbool()"
1000000 loops, best of 3: 0.322 usec per loop
> python -m timeit -s "import random" "random.choice([False, True])"
100000 loops, best of 3: 2.03 usec per loop
> python -m timeit -s "import random" "random.randint(0, 1)"
100000 loops, best of 3: 2.9 usec per loop
So, the fastest is inlining, followed by a regular function, then defining random.randbool
. choice
and randint
are far slower.