Does continued continuation of a backslash line in Python?

I understand that the current best practice for continuing a line is to use the implied continuation in parentheses. For example:

a = (1 + 2 + 3 + 4) 

From PEP8 ( https://www.python.org/dev/peps/pep-0008/ ):

The preferred way to wrap long strings is to use line continuation under Python in parentheses, brackets, and curly braces. Long strings can be split into multiple lines, wrapping expressions in parentheses. They should be used instead of using a backslash to continue the line.

I intend to follow this convention in the future, however, my question is about how I worry about having errors in existing code that continues backslash lines:

 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 space at the end of a line after a backslash can make the code thin thin incorrectly, however, as pointed out in this question ( How can I use the incorrect continuation of the Python reverse mower line? ), the above example simply leads to a syntax error that is not a subtle problem because it is easily identifiable. So my question is: do they exist cases where continuation of the line with a backslash causes something worse than osh Parsing code? I'm interested in examples where an error in continuing a backslash gives an exception at runtime or, even worse, code that works silently but with unintended behavior.

+7
python syntax backslash
source share
3 answers

In one case, I can remember when the programmer forgot \ . This is especially likely when someone comes in and adds values ​​at a later date. Although this example is still somewhat contrived, because continuation lines should have the same level of indentation (otherwise it will fail with an IndentationError).

Example:

 a = 1 \ + 2 \ + 3 assert a == 6 

Someone later adds the line:

 a = 1 \ + 2 \ + 3 # Whoops, forgot to add \ ! + 4 assert a == 10 # Nope 
+3
source share

The "subtle mistake" is subjective; each of them has its own tolerance for subtlety.

One often cited example of a possible possible line continuation, regardless of the \ -separated or implicit, is the continuation of the lines in the container structure:

 available_resources = [ "color monitor", "big disk", "Cray" "on-line drawing routines", "mouse", "keyboard", "power cables", ] 

Are resources available including the Cray supercomputer or the Crayon-line drawing routines ? (This example is from C Expert Programming, adapted for Python here.)

This code block is not ambiguous, but its appearance, created by the continuation + indentation, can be deceiving and can cause a human error in understanding.

+2
source share

I think @ 0x5453 if you mistakenly added a backslash to your code.
This backslash causes the comment to be consistent with.

 a = "Some text. " \ """Here are some multiline comments that will be added to a""" 
0
source share

All Articles