如何保持 kwarg 的 dtype 完整?

How do I keep the dtype intact of a kwarg?

对于我正在处理的脚本,我想让它成为将数组传递给函数的可选选项。我尝试这样做的方法是使相关变量 (residue) 成为 kwarg

问题是,当我这样做时,python 将 kwarg 的数据类型从 numpy.ndarray 更改为 dict。最简单的解决方案是使用以下方法将变量转换回 np.array

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

但我认为这不是一个非常优雅的解决方案。所以我想知道是否有人可以向我展示一种 "prettier" 方法来完成此操作,并可能向我解释为什么 python 这样做?

有问题的函数是:

    #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

使用以下命令调用函数:

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

我工作的Python版本是2.7.15

参见 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.

换句话说,您描述的行为正是语言所保证的。

这种行为的原因之一是底层语言(例如 C/J)中的所有函数、包装器和实现都将理解 **kwargs 是参数的一部分,应该扩展到它的键值组合。 如果你想将你的额外参数保存为某种类型的对象,你不能使用 **kwargs 这样做;通过显式参数传递它,例如extra_args 没有特殊含义。