如何理解Python函数中的一行死代码?

huangapple go评论92阅读模式
英文:

How to understand a line of dead code in a python function?

问题

以下是您要翻译的部分:

  1. def t_newline(t):
  2. r'\n+'
  3. t.lexer.lineno += t.value.count("\n")
英文:

The following code comes from Ply, python’s lexer and parser. I understand the first line is a raw string but I also feel that the first line of the code looks like dead code and will be discarded in execution. How could I understand that line of code?

  1. def t_newline(t):
  2. r'\n+'
  3. t.lexer.lineno += t.value.count("\n")

答案1

得分: 4

  1. It's actually a docstring, so that's not "dead code".
  2. ```python
  3. def t_newline(t):
  4. r'\n'
  5. t.lexer.lineno += 1
  6. t_newline.__doc__
  7. '\n'

ply.lex consumes them.

  1. <details>
  2. <summary>英文:</summary>
  3. It&#39;s actually a docstring, so that&#39;s not &quot;dead code&quot;.

>>> def t_newline(t):
... r'\n'
... t.lexer.lineno += 1
...
>>> t_newline.doc
'\n'

  1. [`ply.lex`](https://github.com/dabeaz/ply/blob/66369a66fa85981ab7a5e1dffd4ff7109bf4fa54/src/ply/lex.py#L323-L330) consumes them.
  2. </details>
  3. # 答案2
  4. **得分**: 1
  5. 那行代码实际上是该函数的文档(尽管其含义不太清晰)。它填充了函数本身的 `.__doc__` 属性。也许 `.__doc__` 属性在代码的其他地方被使用。
  6. 如果你写:
  7. ```python
  8. def myFunc():
  9. '这是我的函数,它始终返回3'
  10. return 3

你将会得到:

  1. print(myFunc.__doc__)
  2. 这是我的函数它始终返回3
英文:

That line of code is actually documentation for the function (although its meaning isn't too clear). It populates the .__doc__ property of the function itself. Perhaps the .__doc__ property is used somewhere else in the code.

If you write:

  1. def myFunc():
  2. &#39;This is my function, it always returns 3&#39;
  3. return 3

you will get:

  1. print(myFunc.__doc__)
  2. This is my function, it always returns 3

huangapple
  • 本文由 发表于 2023年3月7日 11:48:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定