gpt4 book ai didi

python - 为什么 API 作者会阻止 Python 中的位置参数?

转载 作者:行者123 更新时间:2023-11-30 21:58:50 25 4
gpt4 key购买 nike

用 tensorflow 实现一些神经网络,我遇到了一种参数引起了我注意的方法。我说的是tf.nn.sigmoid_cross_entropy_with_logits(文档here)。

它作为第一个参数接收的第一个参数_sentinel=None,根据文档:

_sentinel: Used to prevent positional parameters. Internal, do not use.

我知道,通过使用此参数,下一个必须命名而不是位置,这个参数不必使用,但我的问题是。在哪些情况下防止位置参数有一些好处?他们使用这个的主要目标是什么?因为我也可以运行

tf.nn.sigmoid_cross_entropy_with_logits(None, my_labels, my_logits)

所有参数都是位置参数。不管怎样,我想澄清一下,我的问题并不集中在 TensorFlow 上,这只是我找到的示例。

最佳答案

位置参数按照参数的顺序将调用者和接收者耦合起来。它使得重构接收器参数的顺序变得更加困难。

例如,如果我有

def foo(a, b, c):
do_stuff(a,b,c)

出于某种原因,我决定也许我想做一个部分功能或其他什么,最好有

def foo(b, a, c):
do_stuff(a,b,c)

但现在我在野外有来电者,改变我的契约(Contract)是非常不礼貌的,所以我陷入了困境。

Sandi Metz 在《Ruby 中的实用面向对象设计》中也解决了这个问题。 (我知道这是python,但oop就是oop)

When the code [is changed to use keyword arguments], it lost its dependency on argument order but it gained a dependency on the names of the keys in the [keyword arguments]. This change is healthy. The new dependency is more stable than the old, and thus this code faces less risk of being forced to change. Additionally, and perhaps unexpectedly, the [keywords] provides one new, secondary benefit: The key names in the hash furnish explicit documentation about the arguments. This is a byproduct of using a hash but the fact that it is unintentional makes it no less useful. Future maintainers of this code will be grateful for the information.

如果您有很多参数,关键字参数也很好。顺序很容易出错。在作者看来,它也可能会成为一个更好的 API。

PEP-3102也解决了这个问题,但从“为什么我会选择设计这样的东西”的角度来看,我发现其理由并不令人满意

The current Python function-calling paradigm allows arguments to be specified either by position or by keyword. An argument can be filled in either explicitly by name, or implicitly by position.

There are often cases where it is desirable for a function to take a variable number of arguments. The Python language supports this using the 'varargs' syntax (*name), which specifies that any 'left over' arguments be passed into the varargs parameter as a tuple.

One limitation on this is that currently, all of the regular argument slots must be filled before the vararg slot can be.

This is not always desirable. One can easily envision a function which takes a variable number of arguments, but also takes one or more 'options' in the form of keyword arguments. Currently, the only way to do this is to define both a varargs argument, and a 'keywords' argument (**kwargs), and then manually extract the desired keywords from the dictionary.

关于python - 为什么 API 作者会阻止 Python 中的位置参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54796119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com