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?
Answers:
The answer is two-part:
-
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.
-
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.
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?
The answer is two-part:
-
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.
-
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.