Python 文档参数语法的解释

Explanation of Python doc argument syntax

有人能帮我理解传递给 Python 文档中某些方法的参数的语法吗?

让我感到困惑的例子来自 iter() 函数

iter(o[, sentinel])

根据我的理解,这相当于

iter(o, sentinel)

但是至于为什么我真的不明白

function(mandatory_argument[, optional_argument] 表示可选参数,如果提供该参数将改变函数。在 iter() documentation:

The first argument is interpreted very differently depending on the presence of the second argument.

可选参数以何种方式改变函数应该在它的文档中描述。

可选参数可以嵌套,因此您可能会看到类似 (source):

的内容
bytearray([source[, encoding[, errors]]])

这意味着每个参数都是可选的,但建立在前面的参数之上。所以以下都是有效调用:

bytearray(source)
bytearray(source, encoding)
bytearray(source, encoding, errors)

但这不是:

bytearray(source, errors=errors)

还有第二种方式表明参数是可选的:

__import__(name, globals=None, locals=None, fromlist=(), level=0)

这告诉我们所有这些参数(但名称)都是可选的,并且还告诉我们当我们不为它们提供参数时的默认值。

在纯 python 的代码站点上,您可以通过以下方式获取可选参数:

def iter(o, sentinel=None):
    [do something]

但这不会按照上面的方式记录下来,正如我们在 __import__:

的示例中看到的那样
__import__(name, globals=None, locals=None, fromlist=(), level=0)

要了解为什么 iter 不同,请阅读我的 post.

末尾的部分

另请注意,在 iter() 内置示例中,您可以 提供 sentinel 作为关键字参数,尝试将引发 TypeError:

>>> iter([], sentinel=None)
Traceback (most recent call last):
   File '<stdin>', line1, in <module>
TypeError: iter() takes no keyword arguments

在其他情况下,尽管可能:

>>> bytearray('', encoding='UTF-8')
bytearray(b'')

提供后面的参数而不提供前面的参数仍然会引发错误。

>>> bytearray('', errors='')
Traceback (most recent call last):
  File '<stdin>', line 1, in <module>
TypeError: string argument without an encoding

"keyword like syntax" 是在 python 中记录可选参数的 "normal" 方式。为什么 iter 不同? iter 是一个内建函数,不是在 python 中实现的,而是在 C 中实现的。如果我们查看它的 source code ,我们会发现它将参数视为一个可能有一个或两个参数的元组.

builtin_iter(PyObject *self, PyObject *args)
{
    PyObject *v, *w = NULL;

    if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
        return NULL;
    if (w == NULL)
        return PyObject_GetIter(v);
    if (!PyCallable_Check(v)) {
        PyErr_SetString(PyExc_TypeError,
                "iter(v, w): v must be callable");
        return NULL;
    }
    return PyCallIter_New(v, w);
}

这或许可以解释 "list-like syntax"。似乎 [optional_argument] 符号只用于用 C 编写的模块。对于普通用户来说,如果有

没有区别
function([optional_argument])

function(optional_argument=True)

方括号表示所讨论的参数是可选的。

iter(o[, sentinel])

即上面的例子意味着 iter 是一个带有一个强制参数 o 和一个可选参数 sentinel 的函数.

这意味着您可以像这样调用此函数:

iter(o)  # Method 1

或者像这样:

iter(o, sentinel)  # Method 2

函数的行为取决于您使用的是方法 1 还是方法 2,如文档中的文本所述:

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, o must be a collection object which supports the iteration protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.