【问题标题】:Python accepts keyword arguments in CPython functions?Python 接受 CPython 函数中的关键字参数?
【发布时间】:2012-11-04 08:03:04
【问题描述】:

我使用python3.3,发现它在一些的CPython函数中接受关键字参数:

>>> "I like python!".split(maxsplit=1)
['I', 'like python!']

但其他一些函数接受关键字参数:

>>> sum([1,2,3,4], start = 10)
Traceback (most recent call last):
  File "<pyshell#58>", line 1, in <module>
    sum([1,2,3,4], start = 10)
TypeError: sum() takes no keyword arguments

我的问题是:这些功能之间有什么区别? CPython 中哪些函数接受关键字参数,哪些函数不接受?当然 - 为什么?

【问题讨论】:

    标签: python keyword-argument python-3.3


    【解决方案1】:

    使用PyArg_ParseTuple() 解析其参数的CPython 函数不支持关键字参数(主要是因为PyArg_ParseTuple() 仅支持位置参数,例如简单序列)。

    这在CPython implementation detailshere中有解释:

    CPython 实现细节: 一个实现可以提供内置的 位置参数没有名称的函数,即使它们 为记录目的而“命名”,因此 不能由关键字提供。在 CPython 中,情况就是这样 用 C 实现的函数,使用 PyArg_ParseTuple() 解析它们的 论据。

    【讨论】:

    • 嗯,但是在 python3.2 中你不能在str.split 中插入关键字参数——这是否意味着他们改变了函数的实现?
    • @slallum,我没有 CPython 的 3.3 版本来确认它,但它确实看起来像 3.3 中的 split() 的实现不再使用 PyArg_ParseTuple()
    • @slallum:是的,实现发生了变化。 3.3 str.split accepts keywords(它使用PyArg_ParseTupleAndKeywords()),但3.2 doesn't
    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2021-09-24
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多