Reputation: 732
I use Python to write scripts. I use main function to call other functions (subfunctions). So every time I add new subfunction I have to add new arguments into main function. How to avoid that?
For example I have 2 subfunctions and 1 main function:
def Func1(arg1, arg2): DoStuff1
def Func2(arg3, arg4): DoStuff2
def MainFunc(arg1, arg2, arg3, arg4):
return Func1(arg1, arg2) + Func2(arg3, arg4)
I wrote a new function:
def NewFunc(arg5, arg6): DoStuff3
Then I must specify arg5, arg6
into MainFunc
:
def Func1(arg1, arg2): DoStuff1
def Func2(arg3, arg4): DoStuff2
def NewFunc(arg5, arg6): DoStuff3
def MainFunc(arg1, arg2, arg3, arg4, arg5, arg5):
return Func1(arg1, arg2) + Func2(arg3, arg4) + NewFunc(arg5, arg6)
How to avoid adding all those sub arguments into main function?
Upvotes: 0
Views: 200
Reputation: 397
def func(arg1, arg2):
pass
def func2(arg3, arg4):
pass
def func3(arg5, arg6):
pass
def main(*args):
return func(*args[:2]) + func2(*args[2:4]) + func(*args[4:6])
Other way:
def func(arg1, arg2, **kwargs):
pass
def func2(arg3, arg4, **kwargs):
pass
def func3(arg5, arg6, **kwargs):
pass
def main(**kwargs):
return func(**kwargs) + func2(**kwargs) + func(**kwargs)
Upvotes: 2
Reputation: 73460
You could use argument unpacking, and define your functions accepting an arbitrary number of positional arguments:
def func1(*args): # do stuff 1
def func2(*args): # do stuff 2
def new_func(*args): # do stuff 3
def main_func(*args):
return func1(*args[:2]) + func2(*args[2:4]) + new_func(*args[4:])
But, it won't be more readable and it won't be as explicit as what you have so far. Both of those do count!
Upvotes: 2
Reputation: 11345
You can combine multiple arguments into one tuple param and use it like this
def Func1(arg1, arg2): DoStuff1
def Func2(arg3, arg4): DoStuff2
def MainFunc(*arg):
return Func1(arg[0], arg[1]) + Func2(arg[2], arg[3])
Upvotes: 2