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

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

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

问题

以下是您要翻译的部分:

def t_newline(t):
    r'\n+'
    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?

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

答案1

得分: 4

It's actually a docstring, so that's not "dead code".

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

t_newline.__doc__
'\n'

ply.lex consumes them.


<details>
<summary>英文:</summary>

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'


[`ply.lex`](https://github.com/dabeaz/ply/blob/66369a66fa85981ab7a5e1dffd4ff7109bf4fa54/src/ply/lex.py#L323-L330) consumes them.

</details>



# 答案2
**得分**: 1

那行代码实际上是该函数的文档(尽管其含义不太清晰)。它填充了函数本身的 `.__doc__` 属性。也许 `.__doc__` 属性在代码的其他地方被使用。

如果你写:

```python
def myFunc():
    '这是我的函数,它始终返回3'
    return 3

你将会得到:

print(myFunc.__doc__)

这是我的函数它始终返回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:

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

you will get:

print(myFunc.__doc__)

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:

确定