zell
zell

Reputation: 10204

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

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

Upvotes: 2

Views: 100

Answers (2)

Alain T.
Alain T.

Reputation: 42133

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

Upvotes: 1

wim
wim

Reputation: 363173

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.

Upvotes: 4

Related Questions