这是一个实现细节.
Python C API to retrieve arguments将位置和关键字参数分开.位置参数内部甚至没有名称.
用于检索operator.add函数(以及类似sub)的参数的代码是:
PyArg_UnpackTuple(a,#OP,2,2,&a1,&a2)
如您所见,它不包含任何参数名称.与operator.add相关的整个代码是:
#define spam2(OP,AOP) static PyObject *OP(PyObject *s, PyObject *a) { \
PyObject *a1, *a2; \
if(! PyArg_UnpackTuple(a,#OP,2,2,&a1,&a2)) return NULL; \
return AOP(a1,a2); }
spam2(op_add , PyNumber_Add)
#define spam2(OP,ALTOP,DOC) {#OP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, \
{#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)},
spam2(add,__add__, "add(a, b) -- Same as a + b.")
如您所见,使用a和b的唯一位置是docstring.方法定义也不使用METH_KEYWORDS标志,该标志是接受关键字参数所必需的.
一般来说,你可以放心地假设一个基于python的函数,你知道一个参数名称将始终接受关键字参数(当然有人可以使用* args解包但创建一个函数doc,其中参数看起来正常),而C函数可能会也可能不会接受关键字参数.有多个参数或可选参数的函数接受后来/可选参数的关键字参数,这是很好的.但你几乎要测试它.
您可以在python-ideas mailinglist找到关于支持关键字参数的讨论.还有来自Guido van Rossum(Benevolent Dictator For Life又称Python的创建者)的声明:
Hm. I think for many (most?) 1-arg and selected 2-arg functions (and
rarely 3+-arg functions) this would reduce readability, as the example
of ord(char=x) showed.
I would actually like to see a syntactic feature to state that an
argument cannot be given as a keyword argument (just as we already
added syntax to state that it must be a keyword).
One area where I think adding keyword args is outright wrong: Methods of built-in types or ABCs and that are overridable. E.g. consider the pop() method on dict. Since the argument name is currently undocumented, if someone subclasses dict and overrides this method, or if they create another mutable mapping class that tries to emulate dict using duck typing, it doesn’t matter what the argument name is — all the callers (expecting a dict, a dict subclass, or a dict-like duck) will be using positional arguments in the call. But if we were to document the argument names for pop(), and users started to use these, then most dict sublcasses and ducks would suddenly be broken (except if by luck they happened to pick the same name).