简体   繁体   中英

How can I give an argument without knowing its name to a multiparameter function? Python

Hi I have a multiparameter function where only one parameter is missing in a kwargs and I want to be able to input the missing parameter without knowing what parameter it is:

def function(a,b,c):    #multiparameter function
    print('a=',a)
    print('b=',b)
    print('c=',c)

kwargs={'a':1,'b':2}    #only the value for c is missing

If I run function(3,**kwargs) it interprets that a=3 but I want it to interpret that c=3

Alternatively I could find out the name of the missing variable but I cannot manage to feed it correctly to the function. I tried to do:

variable='c'

function(variable=3,**kwargs)

But it returns the error function() got an unexpected keyword argument 'variable'

If you can't modify the definition of function , you can wrap it with functools.partial .

from functools import partial

def function(a,b,c):    #multiparameter function
    print('a=',a)
    print('b=',b)
    print('c=',c)

function_caller = partial(function, 1, 2, 3)

Now, any keyword arguments to function_caller will override the values specified in the call to partial :

function_caller()  # function(1,2,3)
function_caller(a=5, b=4) # function(5, 4, 3)
kwargs = {'a': 5, 'b': 4}
function_caller(**kwargs)  # Same as previous call

If you have variable that contains the name of a parameter, you can easily add that to kwargs , though you can't use it directly as a keyword argument.

variable = 'c'
kwargs = {'a': 5, 'b': 4, variable: 3}  # {'a': 5, 'b': 4, 'c': 3}

function_caller , though, does not accept any positional arguments.

First, you should probably read about *args and **kwargs

You can force you parameters to be keyword parameters with * and each of your keyword param can have a default sentinel value to help you spot it.

def function(*,a = None,b = None,c = None)
    print('a=',a)
    print('b=',b)
    print('c=',c)

If you want to input something on the fly you could do:

def function(input, *,a = None,b = None,c = None)
    print('a=',a or input)
    print('b=',b or input)
    print('c=',c or input)

If you can take the parameter as a variable, then this request:

 kwargs={'a':1,'b':2} #only the value for c is missing variable='c' function(variable=3,**kwargs)

Can work if you just add the variable to the kwargs dictionary:

kwargs[variable] = 3
function(**kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM