Categories
Mastering Development

Choosing a function randomly and calling it with the appropriate attributes in Python

The answers to Choosing a function randomly tell us how to pick and call a random function from a list using random.choice.

But what if the functions in the list take different attributes? How do we call the function with the appropriate attributes?

Example:

from random import choice

def fun_1():
    ...
def fun_2(x: int):
    ...
def fun_3(y: bool):
    ...

my_integer = 8
my_boolean = True

random_function_selector = [fun_1, fun_2, fun_3]

print(choice(random_function_selector)(???))

The function fun_1 takes no attributes. Whenever fun_2 is selected, I want to call it with my_integer, and whenever fun_3 is selected, I want to call it with my_boolean.

What do I put in the brackets in the last line?

Do I have to rely on if statements to check what random function was selected, and choose the appropriate attribute based on that? Or is there a shortcut?

Leave a Reply

Your email address will not be published. Required fields are marked *