Skip to content Skip to sidebar Skip to footer

How To Randomly Select Functions Within A Function In Python

I have two functions doing different operations but I would like them to be called in another function randomly. eg. def func1(): do something def funct2(): do something else def

Solution 1:

Collect the functions in a list and randomly choose one of them (using random.choice) and call it!

>>>deff2():
        return 2

>>>deff1():
        return 1

>>>fns = [f1, f2]>>>from random import choice>>>choice(fns)()
1
>>>choice(fns)()
2

This is possible because Python functions are first class objects. Read up this link on first class objects in Python.

Post a Comment for "How To Randomly Select Functions Within A Function In Python"