Python : optional arguments for function calling l

2019-07-27 12:22发布

问题:

I have a function

def weights(vector, loss_function, clipping, max_iterations=100, tolerance=1e-5)

which needs to call a lower level loss function which can be any of these with the vector and clipping passed in argument :

huber_loss(vector, clipping=2.38) cauchy_loss(vector, clipping=3.27) bisquare_loss(vector, clipping=1.04)

Each loss function has a special proper default clipping value so we can call them either huber_loss(vector) or huber_loss(vector,2) for example.

I want to make the clipping parameter optional in weights() without giving a default value at weights' level because this would give the same default to all loss functions and that's wrong.

How to make the clipping parameter optional in weights so that if we don't give a value it uses the default value of the specific loss function ? (I know we can set default clipping=None and test in the loss function if clipping=None then set clipping = 2.38 etc.. but I think there's a much more elegant way to do it).

I tried to solve the problem that way :

weights(vector, loss_function, max_iterations=100, tolerance=1e-5, *clipping)

but if we want to give a specific value to clipping without specifying max_iterations and tolerance it doesn't work.

Any idea how to solve this in a pythonic and elegant way ?

回答1:

def weights(vector, loss_function, clipping=None, 
            max_iterations=100, tolerance=1e-5)

kwargs = {}
if clipping:
    kwargs['clipping'] = clipping

huber_loss(vector, **kwargs)


回答2:

You can use max_iterations, tolerance and clipping as **kwargs and check for presence of keys inside arguments

def weights(vector, loss_function, **kwargs):
  if kwargs['max_iterations']:
    max_iterations = kwargs['max_iterations']
  else:
    max_iterations = 100
  ... # and so go on for clipping and tolerance

weights(vect, lf, maxa_iterations=5, clipping=2) 

you dont need to pass all kwargs that you check

PS. If you find an answer that is what you need - accept it :)