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

77 Views Asked by At

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")
2

There are 2 best solutions below

2
wim On BEST ANSWER

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

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

ply.lex consumes them.

1
Alain T. On

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():
    'This is my function, it always returns 3'
    return 3

you will get:

print(myFunc.__doc__)

This is my function, it always returns 3