简体   繁体   English

Python中带有海象运算符的下划线变量

[英]Underscore variable with walrus operator in Python

In Python, the variable name _ (underscore) is often used for throwaway variables (variables that will never be used, hence do not need a proper name).在 Python 中,变量名_ (下划线)通常用于一次性变量(永远不会使用的变量,因此不需要正确的名称)。

With the walrus operator, := , I see the need for a variable that is rather short lived (used in say only one line of code).使用海象运算符:= ,我看到需要一个相当短暂的变量(例如仅用于一行代码)。 I wonder if the use of _ is reasonable to use also in this case, or if it might be confusing for someone reading the code?我想知道在这种情况下使用_是否也是合理的,或者它是否可能会让阅读代码的人感到困惑?

Example:例子:

a = (dummy := pd.Series([1, 2, 3, 4, 5]))[dummy > 2]

Here a pandas series is created and immediately filtered.这里创建了一个熊猫系列并立即过滤。 The name dummy could in my opinion be replaced with _ :在我看来,名称dummy可以替换为_

a = (_ := pd.Series([1, 2, 3, 4, 5]))[_ > 2]

I think it isn't enough reasonable to use underline because it has already been used twice in the code.我认为使用下划线不够合理,因为它已经在代码中使用了两次。

Even if you don't use the dummy variable anymore, it's less readable in the code now.即使您不再使用虚拟变量,现在代码中的可读性也会降低。

You are using the variable dummy , to filter the series.您正在使用变量dummy来过滤系列。 Therefore, don't replace it with _ .因此,请勿将其替换为_

My point of view differs from guys'.我的观点与男生不同。 _ isn't really special as a name, it's a convention mostly for linters to ignore "unused variable" warnings. _作为一个名字并不是很特别,它是一种约定,主要是为了让 linter 忽略“未使用的变量”警告。 So it can be used like you suggested.所以它可以像你建议的那样使用。 A somewhat convoluted example:一个有点复杂的例子:

>>> [_ := i ** 2
...  for i in (6, 5, 4, 3, 2)
... ][_]
4

So you can absolutely use underscore in your example.所以你绝对可以在你的例子中使用下划线。 Whether you should , is a question of personal preference.是否应该,是个人喜好的问题。 Authors of two earlier answers seem to dislike such usage, while I personally tend to favour it.两个较早答案的作者似乎不喜欢这种用法,而我个人倾向于赞成它。

In my opinion, it indicates that this variable is not used outside of this line of code.在我看来,它表明这个变量没有在这行代码之外使用。 It stands out visually enough for the line to be readable, while taking only one character.它在视觉上足以使该行可读,同时只占用一个字符。 Some linters report one-letter variable names, so _ has an advantage there.一些 linter 报告一个字母的变量名,所以_在那里有优势。

It might surprise those who are not accustomed to such usage of underscores, but it still is readable and intuitive enough not to be really confusing.那些不习惯下划线用法的人可能会感到惊讶,但它仍然具有足够的可读性和直观性,不会让人感到困惑。

But then again, it is a personal preference.但话又说回来,这是个人喜好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM