Is it a good idea to define my own random.randbool?
Question: 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.


Answer: In **Ruby** quite common is to implement mixins, that enhance methods
available for classes from _standard library_. Lot of Rails stuff is built
that way.

But I didn't see any indications that would show that this is good practice in
Python. If standard modules lack some feature, it's quite common to create
your own module. The advantage of that is you do not to create impression that
some function/method comes from standard set for anyone else who may look into
your code. I think most _Pythonistas_ trust imports they see at the beginning
of the module.

I can't answer if your approach is slower. I had to '_patch_ ' original Python
libraries in the past by using meta-programming, but that was done to make
sure we have consistent interface for test methods.

