1

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.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Mathio
  • 23
  • 3
  • I added a second duplicate (that covers passing the collected `*args` to another function). Between the two of them, your question is entirely answered. – ShadowRanger Dec 13 '22 at 22:19
  • On "can I pass None instead of function?" What would you expect it to do if you passed `None`? Just not call the function and use the default? Where does that come from? The sole non-duplicate part of your question is rather underspecified. – ShadowRanger Dec 13 '22 at 22:31

1 Answers1

2

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)
kindall
  • 178,883
  • 35
  • 278
  • 309
  • 1
    I've been using kwargs for years, how do i claim my extra bonus points? – Chris_Rands Dec 13 '22 at 22:03
  • Should also put a `/` so that you're allowed to take a keyword argument called `func_to_call` – o11c Dec 13 '22 at 22:03
  • Thanks, but what about my second question of default values for `val` in case no function was provided (I want to allow such thing) – Mathio Dec 13 '22 at 22:08
  • I can't do `*args = None` which means I can't pass functions which don't take any parameters... – Mathio Dec 13 '22 at 22:13
  • You want an empty tuple, `()`, not `None`, if you have no args. – kindall Dec 14 '22 at 14:14
  • You can use `callable()` to test the function to see if it's callable. If not, return that argument or another value as a default. – kindall Dec 14 '22 at 15:11