0

Imagine this situation:

def foo1(item1, item2, item3):
    pass


def foo2(item4, item5):
    pass


item_to_pass = "random item"
x = 3

I need to call one of the functions which takes x arguments. As parameters, I want to pass item_to_pass (or any other variable).

Basically, I know how to find out how many parameters does a function have using inspect module. But what I don't know is how to call a certain function with those arguments (let's say those arguments are all the same). Also note that I can not pass a list of items as an argument instead of multiple parameters, I need to have different amount of arguments and based on that call the function.

Do you have any idea, how could I solve this?

2
  • So, let's say x and y are both arguments. Does that mean only foo2 would be called because only two parameters were passed? And then if x, y, and z were passed, foo1 would be called? Commented Nov 9, 2020 at 12:17
  • Perhaps What does ** (double star/asterisk) and * (star/asterisk) do for parameters? will help you. You can indeed use a list of arguments, passing it as positional arguments. Commented Nov 9, 2020 at 12:25

1 Answer 1

1

Is this what you are looking for:

import inspect

def foo1(item1, item2, item3):
    print("foo1 called")

def foo2(item4, item5):
    print("foo2 called")

def fooWrapper(*args):
    # map functions to function's arguments
    funcs = {fn: len(inspect.getfullargspec(fn).args) for fn in (foo1, foo2)}

    # lookup all functions that take the same amount of arguments as given.
    for fn, argLen in funcs.items():
        if len(args) == argLen:
            fn(*args)
            break

item_to_pass = "random item"
x = 3
foo1_Argument = "foo"

fooWrapper(item_to_pass, x)
fooWrapper(item_to_pass, x, foo1_Argument)

Out:

foo2 called
foo1 called
Sign up to request clarification or add additional context in comments.

Comments

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.