您可以在 Javascript 或 Python 中包含必需的关键字参数吗?

Can you have required keyword arguments in Javascript or Python?

你能在 javascript 或 python 中提供必需的关键字参数吗?这是编程语言的共同特征,还是新的和罕见的?它们类似于 Ruby 2.1+

中 Ruby 关键字参数的实现
def obvious_total(subtotal:, tax:, discount:)
  subtotal + tax - discount
end

obvious_total(subtotal: 100, tax: 10, discount: 5) # => 105

(以上例子直接来自https://robots.thoughtbot.com/ruby-2-keyword-arguments)

我很想知道,因为我对以上页面作者的观点很感兴趣。他基本上建议,必需的关键字参数将帮助编码人员稍后理解彼此的代码,同时只会牺牲简洁性。就个人而言,我认为这是一个不错的权衡,我想知道它是否被普遍采用。

我认为,找到文档不完整的代码并想知道哪个参数做了什么是很常见的事情。这就是为什么我总是尝试在我的方法中加入简洁明了的说明。我可能会疯了,这是一个完全不必要的功能,毕竟,我只是一个新手编码员,当他懒惰时编写脚本。

PEP-3102 引入了 “仅关键字参数”,所以在 Python 3.x 中你可以这样做:

def obvious_total(*, subtotal, tax, discount):
    """Calculate the total and force keyword arguments."""
    return subtotal + tax - discount

正在使用:

>>> obvious_total(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: obvious_total() takes 0 positional arguments but 3 were given
>>> obvious_total(subtotal=1, tax=2, discount=3)
0

在 JavaScript 中根本无法使用关键字参数。这样做的约定是定义一个位置参数,用户将对象文字传递给该位置参数:

function obviousTotal(input) {
    return input.subtotal + input.tax - input.discount
}

然后将对象字面量作为 input 传递。使用中:

> obviousTotal({ subtotal: 1, tax: 2, discount: 3 })
0

ES6 让你可以通过 解构:

稍微简化一下
function obviousTotal({ discount, subtotal, tax }) {
    return subtotal + tax - discount;
}

但是仍然没有对必需关键字参数的本机支持。