A simple single line, triple-quoted comment is giving syntax error. Why?
Thomas 'PointedEars' Lahn
PointedEars at web.de
Wed Mar 18 15:53:30 EDT 2015
Laurent Pointal wrote:
> Laurent Pointal wrote:
>> Take care of indent:
>>
>> def f(x):
>> a = 5
>> """an correctly indented expression to be
>> inside the function"""
>> return a * x
>
> Here only the first indent of """ at beginning of the string to be aligned
> to function bloc is important, remaining content of the string can be
> indented or not.
I must strongly object and recommend against getting accustomed to the
suggested use of multi-line string literals. First of all, it is too easy
to produce invalid code this way. Also, standalone multi-line string
literals in Python code serve a specific purpose when at the beginning of a
function, method or class clock: they constitute *docstrings”, setting the
respective object’s “__doc__” attribute:
>>> def f(x):
... """Returns a multiple of 5"""
... a = 5
... return a * x
...
>>> print(f.__doc__)
Returns a multiple of 5
This means that different to real comments, the content of string literals
is *parsed*. You do not want to waste the time of the compiler compiling
code that serves no purpose; particularly not in a language like Python
where code is JIT-compiled by default.
Not any less important: Using standalone multi-line string literals in any
other way is syntactically correct indeed, but makes the code harder to
read. Keep in mind that code may be written only once, but read many times
by other people during its lifetime. It is important to write code so that
it is easy to read, so that it can be easily reused and adapted by oneself
and others (a month, a year later).
If you want to comment your code, then by all means do so using docstrings
and *real* comments. IDEs like PyDev support you there. That way also the
syntax highlighting will be correct. And with real comments, the Python
compiler does not care about the indentation. As to where you should put
comments, I recommend in general, in all programming languages, if possible
to put the comments on their own line, *before* the statement that they are
describing, and using the same indentation, preferably preceded by an empty
line (so that the comment and the code it documents stand out).
<https://docs.python.org/3/tutorial/controlflow.html#documentation-strings>
<https://docs.python.org/3/reference/lexical_analysis.html#line-structure>
--
PointedEars
Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
More information about the Python-list
mailing list