Home > OS >  How do I use kwargs to create a master function?
How do I use kwargs to create a master function?

Time:07-24

I have three functions created and they are the following:

StoreInfo(D1)
GetResidual(D1)
FindAlternative(D1)

They all take the same input of "D1".

There are instances where I do not want to use all three of them, so I am attempting to create a master function called "Master()" whose parameters determine which of the three functions I wish to use. I want it to be like the following:

Master(StoreInfo,GetAlternative)

And the function should run both the StoreInfo() and GetAlternative() function.

Is there a way to do this?

CodePudding user response:

You could just call the passed functions:

def master(*functions):
    for function in functions:
        function(D1)

CodePudding user response:

By using a decorator it is possible to control the dependency of the common parameter.

def master(*funcs):
    def wrapper(common_arg):
        for f in funcs:
            f(common_arg)
    return wrapper


def a(D1): print(f'-> a({D1})')
def b(D1): print(f'-> b({D1})')
def c(D1): print(f'-> c({D1})')


master(a, b, c)(common_arg='D1')
#-> a(D1)
#-> b(D1)
#-> c(D1)
master(a, c)(common_arg='D2')
#-> a(D2)
#-> c(D2)
  • Related