-1

I am trying to understand the following syntax. Why is it allowed to pass in arguments that are less than the given outcome? For example,

def fit_curve_custom(f, xdata, ydata, p0=None, sigma=None, **kwargs):
   po, pc = curve_fit(f, xdata, ydata, p0, sigma, **kwargs)

def fit(x, a, b, c):
   return a*exp(b)+c

(po, pun, rac, de) = fit_curve_custom(fit, xsamples, yobserved)

In the above code fit_curve_custom has six arguments however when it is called later there are only three arguments passed and yet it still behaves as expected? Does this syntax actually have a name? Also, the function fit has four parameters and yet when it is called in fit_curve_custom no parameters are passed? Why is that possible?

martineau
  • 119,623
  • 25
  • 170
  • 301
Robben
  • 457
  • 2
  • 8
  • 20
  • 2
    See [More on defining functions](https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions) in the standard tutorial. – tdelaney Aug 12 '20 at 00:13
  • 1
    The syntax is called a function having default arguments. Also, `fit_curve_custom ` _doesn't_ call the `fit()` function. – martineau Aug 12 '20 at 00:16
  • @martineau What do you mean that it doesn't call the fit function? the fit function is passed in the `fit_curve_custom` function – Robben Aug 12 '20 at 00:23
  • @tdelaney that link helps, ty – Robben Aug 12 '20 at 00:24
  • There is no call to the passed `fit()` function in the `fit_curve_custom()` function. – martineau Aug 12 '20 at 00:27
  • You have 2 questions here: 1 is defining optional parameters for a function, 1 is how to *__pass__* functions as arguments to another function. – Gino Mempin Aug 12 '20 at 00:56

1 Answers1

1
fit_curve_custom(fit, xsamples, yobserved)

This is possible because the last two parameters of fit_curve_custom are optional argument or named arguments

If there are not passed the will have an default value p0=None, sigma=None

The last kwargs is a keyword arguments which is python convention that allows passing into function a dict of named argument, inside the function they can be accessed kwargs['arg1']

for example :

fit_curve_custom(fit, xsamples, yobserved, p1 = None, sigma = None, arg1 = 'a', arg2 = 'b')

In fit_curve_custom(fit, xsamples, yobserved), fit here is actually not called, it is passed to fit_curve_custom function ( functions can be passed as regular values) and the be called, like :

def fit_curve_custom(f, xdata, ydata, p0=None, sigma=None, **kwargs):
   calc_res = f(10, 10, 10, 10) #  call f
   po, pc = curve_fit(f, xdata, ydata, p0, sigma, **kwargs) #  f is passed to another function
AnGG
  • 679
  • 3
  • 9