1

I have a function A with two named parameters and a function B that will optimize the result of A, changing its arguments. The algorithm is the same regardless I optimize the first or the second parameter. Can I pass to B the name and the value of needed parameter? The question raised while looking at scikit-learn functions of machine learning.

I want something like this:

def A(p1 = 0, p2 = 0):
   print(p1 + p2)
def B(par_name, par_val):
    ...

B will call A with given parameter.

B("p1", 1) => A(p1 = 1, p2 = 0)
B("p2", 1) => A(p1 = 0, p2 = 1)

3 Answers 3

2

You can call A with the keyword argument that you need. In a similar case i put the arguments from the calling function in a dict and pass his to the called function

def A(p1 = 0, p2 = 0):
  print(str(p1) + str(p2))
def B(par_name, par_val):
   para_dict = dict()
   para_dict[para_name] = para_val
   A(**para_dict)

Please see Key Word Arguments in the python docs for more details.

another way is, that your dict already has all keys p1, p2 with its default values and you are just update the key you want and pass it to A

para_dict = {"p1":0,"p2":0}

and it might be better to loop through the arguments in A

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

Comments

0

Yes, it is possible to use named arguments when calling another functions:

 def A(p1, p2):
   print("p1=%s, p2=%s" % (p1, p2))

 def B():
   A(p2="two", p1="one")

 >>> B()
 p1=one, p2=two

2 Comments

Thanks, but I want a bit another effect, see edited question.
IFrom you example it's not clear how does p1 become 1 and 1(2nd arg) become 0
0

The number and names of the parameters are fixed? If so, the best way is passing a dict as Joe Platano has mentioned. Otherwise you can also do

>>> def A(p={}):
       # to print?
...    print(p.get('p1',0),' + ',p.get('p2',0))
       # or to compute?
...    print(p.get('p1',0) + p.get('p2',0))
...
>>> def B(key, value):
...     A(p={key:value})
...
>>> B('p1',1)
1  +  0
1
>>> B('p2',1)
0  +  1
1

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.