Mathio
Mathio

Reputation: 23

Python Function, get function and arguments as parameters?

Note: The referenced duplicate questions doesn't fully answer my current problem.

In Python, I know how to pass a function as an argument, but how to pass its parameters too (which I don't how many they will be. ie a variable number)

for example, I tried:

def general_func(func_to_call, args):
   val = func_to_call(args)
   ...

But here args is one single element, what if the function func_to_call takes 2 arguments? I want something like this:

general_func(test_function, p1, p2, p3)

Plus can I pass None instead of function? I've some cases in which if the user doesn't send parameters to general_func then to give val a default value.

Upvotes: 1

Views: 437

Answers (1)

kindall
kindall

Reputation: 184101

Use the * operator.

def general_func(func_to_call, *args):
    val = func_to_call(*args)

For extra bonus points, use ** to accept keyword arguments as well.

def general_func(func_to_call, *args, **kwargs):
    val = func_to_call(*args, **kwargs)

Upvotes: 2

Related Questions