Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass all element of a list as parameter of a function without passing the list as argument

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is this possible ?
Best regards.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading