3

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

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

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.

我遇到的问题是我看不到一种明确的方法来告诉用户参数部分中的哪些参数是关键字与非关键字,因此我必须执行以下操作:

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
'''

where:表示它是非关键字(即。SomeFunc(100, 200))并=表示关键字(即。SomeFunc(100, 200, name="Bob", label="one and two hundred")

4

1 回答 1

-2

当参数是 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
...
于 2015-02-02T02:21:55.943 回答