为什么在 python 3.8 中只使用位置参数?

Why use positional only arguments in python 3.8?

3.8 中引入了新的 "positional only arguments" 语法。

来自文档中的Positional-only parameters

There is new syntax (/) to indicate that some function parameters must be specified positionally (i.e., cannot be used as keyword arguments). This is the same notation as shown by help() for functions implemented in C (produced by Larry Hastings’ Argument Clinic tool).

来自http://northtexasroofing.net/article/10509084.shtml

Now pow(2, 10) and pow(2, 10, 17) are valid calls, but pow(x=2, y=10) and pow(2, 10, z=17) are invalid.


我的问题是,为什么要使用这种语法?

为什么代码的用户更好?

在我看来,这让用户更难具体说明他们的论点的实际含义,如果他们愿意的话。

为什么要让用户更难?

我显然遗漏了一些东西。

为了简要总结 PEP 570 中陈述的基本原理,添加了仅位置参数的 PEP:

  1. 许多用 C 实现的内置函数已经不接受关键字参数,甚至在 Python 3.8 之前也是如此。允许仅位置参数允许 python 代码与 C 代码一致
  2. 一些 python classes,例如 dict 类型的构造函数,采用任意关键字参数。如果您尝试在 python 中定义具有此类行为的 class,则必须编写 def __init__(self, **kwds),...除非您不能使用名为 [= 的关键字参数12=]!。仅位置参数可以避免此缺陷。
  3. 一些函数没有任何自然名称来分配它们的参数。以 int 构造函数为例。 int(x="3") 并不比 int("3") 更具可读性。仅位置参数允许将没有内在含义的名称视为实现细节,而不是模块 public API 的一部分。

PEP 中还有更多细节,但这三点总结了该功能存在的一般原因。