This is the example :
def testB(argA, argB):
#USER CODE
def testA(argA, argB, argC):
#USER CODE
def funcExecuter(func, nbArgs, *argv):
#TODO
funcExecuter(testA, 3, 1, 2, 3)
funcExecuter(testB, 2, 1, 2)
I want to implement a function (here funcExecuter) that execute the function func with its arguments that are in argv. Thoses functions got undefined number of parameters. But i can't call
func(*argv)
cause the actual function testA, needs three parameters not one. So i need to uses argv list to call the function func with all its parameters.
Is this possible ? Best regards.
CodePudding user response:
It looks like what you do is the correct method.
Example:
def testB(argA, argB):
print(f'{argA=}')
print(f'{argB=}')
def testA(argA, argB, argC):
print(f'{argA=}')
print(f'{argB=}')
print(f'{argC=}')
def funcExecuter(func, nbArgs, *argv):
return func(*argv)
print('test1')
funcExecuter(testA, 3, 'a', 'b', 'c')
print('test2')
funcExecuter(testB, 2, 'a', 'b')
output:
test1
argA='a'
argB='b'
argC='c'
test2
argA='a'
argB='b'
ensuring the correct number of parameters
If you want to truncate or pad the parameters:
def testA(argA, argB, argC):
print(f'{argA=}')
print(f'{argB=}')
print(f'{argC=}')
def funcExecuter(func, nbArgs, *argv):
return func(*(list(argv[:nbArgs]) [None]*(nbArgs-len(argv))))
print('test1')
funcExecuter(testA, 3, 'a', 'b', 'c')
print('test2')
funcExecuter(testA, 3, 'a', 'b', 'c', 'd')
print('test3')
funcExecuter(testA, 3, 'a', 'b')
output:
test1
argA='a'
argB='b'
argC='c'
test2
argA='a'
argB='b'
argC='c'
test3
argA='a'
argB='b'
argC=None
NB. this is a simple example here, of course you can have a more complex check
CodePudding user response:
Why don't you use func(*argv)
and just throw an exception if they pass less than 3 arguments?