Home > Software engineering >  how to pass function arguments from json file
how to pass function arguments from json file

Time:05-06

Let me ask you please, how to pass variables defined in json file.

for example.

i have functions as follows.

def fun1(a , b) : 
    print(a , b)

def fun2(c , d) : 
    print(c , d)


jsonfile = {    
    'function1' : {
        'callback' : 'fun1' , 
        'args' : ['a' , 'b']
    }, 
    'function2' : {
        'callback' : 'fun2',
        'args' : ['c' , 'd']
    }
}

# iter the json file looking for the function callback   the args to call them ..
for key , value in jsonfile.items() :
    function_name = value['callback']
    function_args = value['args']
    locals()[function_name](# how to pass the functions args ?? )

when i do that :-

locals()[function_name](function_args)

i get this error. because function think that i am passing only 1 args , not 2

   locals()[function_name](function_args)
TypeError: fun1() missing 1 required positional argument: 'b'

any suggestions ?

CodePudding user response:

List of arguments should be unpacked:

locals()[function_name](*function_args)

CodePudding user response:

You can use the unpacking operator on function_args:

for key , value in jsonfile.items() :
    function_name = value['callback']
    function_args = value['args']
    locals()[function_name](*function_args)

This outputs:

a b
c d
  • Related