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.

2
  • I added a second duplicate (that covers passing the collected *args to another function). Between the two of them, your question is entirely answered. Commented Dec 13, 2022 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. Commented Dec 13, 2022 at 22:31

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

6 Comments

I've been using kwargs for years, how do i claim my extra bonus points?
Should also put a / so that you're allowed to take a keyword argument called func_to_call
Thanks, but what about my second question of default values for val in case no function was provided (I want to allow such thing)
I can't do *args = None which means I can't pass functions which don't take any parameters...
You want an empty tuple, (), not None, if you have no args.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.