A simple single line, triple-quoted comment is giving syntax error. Why?
Tim Chase
python.list at tim.thechases.com
Wed Mar 18 14:15:28 EDT 2015
On 2015-03-18 10:46, Aditya Raj Bhatt wrote:
> a = 5 '''a comment'''
>
> results in a syntax error
That's to be expected, and happens with any string, not just
triple-quoted:
>>> a = 5 "hello"
> there are no 'true' multiline comments in python and that all those
> 'block' comments are actually triple-quoted strings.
Yes, that's an abuse of strings. It works nicely for doc-strings,
but I avoid it for everything else.
> So can someone tell me why a triple-quoted string gives a syntax
> error if only in one line?
When a string (triple-quoted or otherwise) begins at the beginning of
a line, its return value is ignored at compile-time:
>>> def a():
... print 1
... "test"
... print 2
...
>>> import dis
>>> dis.dis(a)
2 0 LOAD_CONST 1 (1)
3 PRINT_ITEM
4 PRINT_NEWLINE
4 5 LOAD_CONST 2 (2)
8 PRINT_ITEM
9 PRINT_NEWLINE
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
Note that nothing appears in the byte-code for line #3. They Python
interpreter/compiler is smart enough to know that the string can be
discarded.
> Actually, there are other confusions I have too, regarding using
> backslashes inside triple-quoted strings to form multi-line
> comments, and a general uncertainty about triple-quoted strings.
>
> Can someone also provide a sort of a 'guide' to triple-quoted
> comments in general?
Triple-quoted strings aren't particularly magical other than that
they allow you to have multi-line strings and it allows you to have
both single and double quotes inside the string with less mess than
if you have them mixed in a regular string (where you'd need to
escape at least one of them).
s1 = "Single ' and double \" quotes"
s2 = 'Single \' and double " quotes'
s3 = """Single ' and double " quotes"""
If you want to avoid some of the backslash issues, you can make it a
raw triple-quoted string:
s = r"""this is in
c:\temp\new>
for you to test
"""
Note the leading "r" before the quotes. This is what tells Python
not to translate the "\t" and "\n" in the following content.
-tkc
More information about the Python-list
mailing list