Welcome, guest | Sign In | My Account | Store | Cart

This (quick but strangely satisfying) recipe combines the use of random.choice with functools.partial from the standard library. It is a factory function returning random.choice pre-filled with its sequence of options.

Python, 9 lines
def picker(seq):
       Returns a new function that can be called without arguments 
       to select and return a random entry from the provided sequence
    from functools import partial
    from random import choice

    return partial(choice,seq)

When writing tests or generating test data I often use the standard library's random.choice function. This function chooses one random element from a sequence passed in as an argument. It becomes tiresome to keep passing the same arguments around so I wrote this function. doctests are tricky with random return values, but this output might be illustrative:

>>> colors = ['Red','Orange','Yellow','Green','Blue']
>>> color_picker = picker(colors)
>>> color_picker()
>>> color_picker()
>>> [color_picker() for c in range(8)]
['Orange', 'Red', 'Blue', 'Yellow', 'Yellow', 'Orange', 'Orange', 'Blue']

The meat of this recipe is one expression ( partial(choice,seq) ). It might be argued that it's not worth packaging this into a function. However, when combined with the inline import statements, it's a handy gadget to include in a test_utils.py or similar module.