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?

Zejak
  • 11
  • 1
  • 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? – gmdev Nov 09 '20 at 12:17
  • Perhaps [What does ** (double star/asterisk) and * (star/asterisk) do for parameters?](https://stackoverflow.com/q/36901/3127242) will help you. You can indeed use a list of arguments, passing it as positional arguments. – Boyan Hristov Nov 09 '20 at 12:25

1 Answers1

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
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47