2

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.

2 Answers 2

5

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:

Sign up to request clarification or add additional context in comments.

Comments

0

I took the liberty of interpreting a bit what the OP said he wanted, i.e. 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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.