问题
I understand that current best practice for line continuation is to use implied continuation inside parenthesis. For example:
a = (1 + 2
+ 3 + 4)
From PEP8 (https://www.python.org/dev/peps/pep-0008/):
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
I intend to follow this convention going forward, however, my question regards how worried I should be about bugs in existing code that continues lines with a backslash:
a = 1 + 2 \
+ 3 + 4
The python docs (https://docs.python.org/2.7/howto/doanddont.html#using-backslash-to-continue-statements) warn that a stray space at the end of a line after the backslash can make the code "subtly wrong," however, as pointed out in this question (How can using Python backslash line continuation be subtly wrong?), the example given simply results in a SyntaxError being raised which is not a subtle problem as it is easily identified. My question, then, is do there exist cases where continuing a line with a backslash causes something worse than a parsing error? I am interested in examples where a mistake in backslash continuations yields a runtime exception or, worse, code that runs silently but with unintended behavior.
回答1:
One case I can think of is when the programmer forgets a \
. This is especially likely when someone comes and adds values at a later date. Though this example is still somewhat contrived because the continuation lines have to have the same indentation level (otherwise it would fail with an IndentationError).
Example:
a = 1 \
+ 2 \
+ 3
assert a == 6
Later, someone adds a line:
a = 1 \
+ 2 \
+ 3 # Whoops, forgot to add \ !
+ 4
assert a == 10 # Nope
回答2:
"Subtly wrong" is subjective; each has her own tolerance of subtlety.
One often-cited example of possibly harmful line continuation, regardless of \
-separated or implicit, is the continuation of strings in a container structure:
available_resources = [
"color monitor",
"big disk",
"Cray"
"on-line drawing routines",
"mouse",
"keyboard",
"power cables",
]
Do the available resources include a Cray supercomputer, or Crayon-line drawing routines
? (This example is from the book "Expert C Programming", adapted for Python here).
This code block isn't ambiguous, but its visual appearance created by continuation + indentation can be deceptive, and may cause human error in understanding.
回答3:
I think like @0x5453, if you wrongly add backslash to your code.
This backslash cause the comment to be concat with a.
a = "Some text. " \
"""Here are some multiline comments
that will be added to a"""
来源:https://stackoverflow.com/questions/48830681/is-line-continuation-with-backslash-dangerous-in-python