-2

Say I have a method:

def A(...)

that needs to be passed into it multiple methods (B, C), which each take an unknown amount of arguments. The possible argument variable names could be known, if this is helpful.

Is there another way I could pass in these arguments (maybe through 2 lists?)

A. Savino
  • 3
  • 2
  • 2
    what did you try so far? – bogdanciobanu Jul 17 '17 at 20:28
  • 1
    `def(f1, dict1, f2, dict2): f1(**dict1); f2(**dict2)` – cs95 Jul 17 '17 at 20:30
  • At the moment this is more of a thought experiment, since I'm not sure how to approach this at all -- I've tried having the function accept **kwargs and searching through the keys to find the appropriate parameters, and thought about passing in 2 lists and passing in those commands through *args – A. Savino Jul 17 '17 at 20:30
  • 1
    Check out: https://stackoverflow.com/questions/817087/call-a-function-with-argument-list-in-python – Dehli Jul 17 '17 at 20:31

2 Answers2

0

Check this out:

def func1(arg1, arg2):
    print("I am func1: arg1 is {} and arg2 is {}".format(arg1, arg2))


def func2(arg1, arg2, arg3):
    print("I am func2: arg1 is {} and arg2 is {} and arg3 is {}".format(arg1, arg2, arg3))


def majorfunc(f1, args1, f2, args2):
    print("I am majorfunc. I call all the funcs")
    print("Now, I am calling f1")
    f1(*args1)
    print("Now, I am calling f2")
    f2(*args2)


def main():
    f1 = func1
    args1 = (1, 2)

    f2 = func2
    args2 = ('a', 'b', 'c')

    majorfunc(f1, args1, f2, args2)
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • Say there are two possibilities for func2: def func2(arg1, arg2, arg3): ... def altfunc2(arg1, arg2): .... So long as the number of arguments passed matches the amount of arguments that version of func2 takes, there will be no error? – A. Savino Jul 17 '17 at 20:39
  • @A.Savino: yes. As long as the number of arguments match, there will be no error. I am confused about what you mean by `two possibilities for func2`. Could you please explain that? – inspectorG4dget Jul 17 '17 at 20:43
0

Yes, you could do what you suggest and pass the arguments as two separate lists:

def A(B, B_args, C, C_args):
    B(*B_args) # Use function B
    C(*C_args) # Use function C

This will get the job done, but something that is slightly ugly about this is that it would prevent the use of keyword arguments with B and C, which is sometimes strongly desired for clarity. Adding separate args and kwargs arguments for each function also seems clumsy.

For a more general approach, I would recommend binding the arguments to the functions outside of the body of A, which would give you the full power of Python's function call mechanisms in a simple way:

import functools

def A(B, C):
    B() # Use function B
    C() # Use function C

# Call A while mix-and-matching positional and keyword args
A(functools.partial(B, 1, 2, 3), functools.partial(C, foo=bar))
mooiamaduck
  • 2,066
  • 12
  • 13