M213081 M213081 - 23 days ago 6
Python Question

Choose a random function

Using python 3.5 is it possible to have a list of definitions and have a function choose and call that random definition? I am asking this because all of the docs I have seen for random just says about generating a random pseudo number.

Answer
>>> def foo(): print('foo')
>>> def bar(): print('bar')
>>> from random import choice
>>> choice([foo, bar])
<function foo at 0x10499d668>
>>> choice([foo, bar])()
foo
>>> choice([foo, bar])()
bar
>>> choice([foo, bar])()
foo