Raw regex string used in function as throw-away statement whose value is discarded

Question:

I was recently browsing the code for pycparser and saw some functions like this:

def t_CPP_WS(t):
    r's+'
    t.lexer.lineno += t.value.count("n")
    return t

How does the r's+' work? There are no function calls (e.g. re.match)or anything wrapped around or using it. I have very little experience with python (mostly javascript), but wouldn’t this get ignored?

Asked By: drvx_alt

||

Answers:

The answer is two-part:

  1. Ordinarily in Python, you would be right: a string that is not assigned to a variable or passed to a function or method that creates some kind of side effect would not produce any overall effects. However, if the first statement in a Python function is a string literal, this string becomes the docstring of that function, a special property that Python functions can possess.

  2. The provided code in that PycParser library is not pure Python, but rather uses the library PLY, which uses Python docstrings in order to define functionality 2.

Thus, the provided code assigns a value to the function’s docstring, and then the PLY library uses that docstring.

Answered By: jaynik
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.