0

For a script that I am working on I want to make it optional to pass on an array to a function. The way in which I have attempted to do this is by making the variable in question (residue) a kwarg.

The problem is that when I do it in this way, python changes de dtype of the kwarg from a numpy.ndarray to dict. The simplest solution is to convert the variable back to a np.array using:

    residue = np.array(residue.values())

But I do not find this a very elegant solution. So I was wondering if someone could show me a "prettier" way to accomplish this and possibly explain to my why python does this?

The function in question is:

    #Returns a function for a 2D Gaussian model 
    def Gaussian_model2D(data,x_box,y_box,amplitude,x_stddev,y_stddev,theta,**residue):
        if not residue:
            x_mean, y_mean = max_pixel(data) # Returns location of maximum pixel value   
        else:
            x_mean, y_mean = max_pixel(residue) # Returns location of maximum pixel value
        g_init = models.Gaussian2D(amplitude,x_mean,y_mean,x_stddev,y_stddev,theta) 
        return g_init
     # end of Gaussian_model2D

The function is called with the following command:

    g2_init = Gaussian_model2D(cut_out,x_box,y_box,amp,x_stddev,y_stddev,theta,residue=residue1)

The version of Python that I am working in is 2.7.15

ChrisVB
  • 3
  • 2

1 Answers1

0

See the accepted answer here why you always get a mapping-object (aka a dict) if you pass arguments via **kwargs; the language spec says:

If the form “**identifier” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type.

In other words, the behavior you described is exactly what the language guarantees.

One of the reasons for this behavior is that all functions, wrappers, and implementations in the underlying language (e.g. C / J) will understand that **kwargs is part of the arguments and should be expanded to its key-value combinations. If you want to preserve your extra-arguments as an object of a certain type, you can't use **kwargs to do so; pass it via an explicit argument, e.g. extra_args which has no special meaning.

user2722968
  • 13,636
  • 2
  • 46
  • 67