简体   繁体   中英

Passing function parameter name to another function in Python

Given a simple function:

def A(a = 1, b = 2):
    return a+b

I want to write another function to change the default parameter value, for either a or b . And user can specify the parameter to change by setting var = a or var = b . For example:

def B(var = 'a', new_value = 10):
    temp_dict = {var:new_value}
    ans = A(var)
    return ans    

or

def B(var = 'a', new_value = 10):
    ans = A(var = new_value)
    return ans

In function def B() , after setting var = a and var = new_value = 10 , I expect A(var = new_value) to achieve the same effect as A(a = 10) . Do you know the correct way to write function def B() ? Thanks.

You are almost there. From your B() function, while making the call to A() , you need to unpack the temp_dict and pass it as an argument to A() . See below:

>>> def A(a = 1, b = 2):
...     return a+b
...

>>> def B(var = 'a', new_value = 10):
...     temp_dict = {var:new_value}
...     ans = A(**temp_dict)
        #        ^ unpack the dict, and pass it as an argument
...     return ans
...

>>> B()
12

For more details on how this ** works with a dict, please take a look at:

I took the liberty of interpreting a bit what the OP said he wanted, ie change the default parameter value, for either a or b . So what I did was to return a transformed function A with either the a or b defaults changed via a partial:

from functools import partial

def B3(var ="a", new_value=10):
    return partial(A, **{var:new_value})

sample outputs:

(Pdb) f = B3("a",10)
(Pdb) f()
12
(Pdb) f = B3("b",10)
(Pdb) f()
11
(Pdb) f(a=10)
20
(Pdb) f(b=13)
14
(Pdb) f(a=5,b=5)
10

That is different from the 2nd half of the request however, that of having something based on B(var="a",new_value=10) as function signature.

The only thing is, it chokes happily if you don't use keyword parameters:

(Pdb) f(7,7)
*** TypeError: A() got multiple values for keyword argument 'b'

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