Home > Blockchain >  TypeError: function missing required positional argument when reading arguments from file
TypeError: function missing required positional argument when reading arguments from file

Time:05-06

How can I pass in variable values that are defined in a JSON file?

I have these two functions:

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:

locals()[function_name](function_args)

I get the following error, because the function thinks that I am passing only 1 argument, 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