Skip to main content
 首页 » 编程设计

python之在 NumpyDoc DocStrings 中指示参数的关键字特性

2025年05月04日898°冷暖

在尝试遵循我的 DocString 的 NumpyDoc 格式时,我似乎无法弄清楚如何告诉用户参数是关键字参数(即指定为 SomeFunc(theKeyWordArg=100) 而不是 SomeFunc(100) )。

我在网上找到的文档(例如 this 和 this )仅显示示例,例如

def somefunc(arg1, arg2): 
''' 
Parameters 
---------- 
arg1, arg2 : int 
    info on arg1 & arg2 

对于关键字参数:

def somefunc( keyword=False ): 
... 

但是对于一般情况来说,这是我在我的许多函数中定义的:

def somefunc( *args, **kwargs): 

我应该这样记录它们:

Parameters 
---------- 
*args 
    Variable length argument list. 
**kwargs 
    Arbitrary keyword arguments. 

我遇到的问题是,我没有看到一种明确的方法来告诉用户 Parameters 部分中的哪些参数是关键字和非关键字,所以我必须做一些事情像下面这样:

somefunc(*args, **kwargs) 
''' 
Parameters 
---------- 
x : int 
    Non-keyworded arg, x is an int 
name : string 
    keyworded arg, pass a string as the name. 
''' 

所以用户会像这样调用函数来设置x & name:

somefunc(10, name='gazebo') 

是否没有标准的方法来在文档字符串中指示哪些参数是关键字,哪些不是?


例如,这不是一个表达清楚的好方法吗?

somefunc(*args, **kwargs) 
''' 
Parameters 
---------- 
x : int 
    x is an int 
y : float 
    y should be a float 
name = string 
    Pass a string as the name 
label = string 
    Provide a label for this object 
''' 

: 表示它是非关键字的(即 SomeFunc(100, 200)),= 表示关键字(即 SomeFunc(100, 200, name="Bob", label="一又二百"))

请您参考如下方法:

当一个参数是 Python 中的关键字参数时,它因此有一个默认值(撇开 **kwargs 的一些不寻常处理)。通常只需说明默认值就足够了(并使文档更简单),例如:

def somefunc(keyword=False): 
    """ 
    Parameters: 
    ----------- 
    keyword: bool. Controls whether to delete hard drive. Defaults to False. 
    ... 
    """ 
    # ... rest of code 

由此,读者必须知道任何具有默认值的参数都是关键字参数。

这是一些较大的库中的样式,例如 pandas。以下是 pandas.ols 的一些帮助字符串:

Definition: pandas.ols(**kwargs) 
Docstring: 
Returns the appropriate OLS object depending on whether you need 
simple or panel OLS, and a full-sample or rolling/expanding OLS. 
 
Will be a normal linear regression or a (pooled) panel regression depending 
on the type of the inputs: 
 
y : Series, x : DataFrame -> OLS 
y : Series, x : dict of DataFrame -> OLS 
y : DataFrame, x : DataFrame -> PanelOLS 
y : DataFrame, x : dict of DataFrame/Panel -> PanelOLS 
y : Series with MultiIndex, x : Panel/DataFrame + MultiIndex -> PanelOLS 
 
Parameters 
---------- 
y: Series or DataFrame 
    See above for types 
x: Series, DataFrame, dict of Series, dict of DataFrame, Panel 
weights : Series or ndarray 
    The weights are presumed to be (proportional to) the inverse of the 
    variance of the observations.  That is, if the variables are to be 
    transformed by 1/sqrt(W) you must supply weights = 1/W 
intercept: bool 
    True if you want an intercept.  Defaults to True. 
nw_lags: None or int 
...