The following is syntactically invalid:
if extremely_long_condition_that_takes_up_a_whole_line and
another_condition:
#do something
The following is valid:
if (extremely_long_condition and
another_condition):
#do something
Why are these different? More generally, why is #2 okay but #1 somehow dangerous/ambiguous? I can't see how the first statement is or generalizes to an ambiguous statement.
Brackets imply line continuation until they are closed.
PEP-8 talks about this:
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.
Or, it is discussed more formally in the language reference:
Two or more physical lines may be joined into logical lines using backslash characters (\)
Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes.
Without the braces, it is definitely ambiguous in the presence of unary operators.
Consider the line:
a = 3 + 4
+1
Here you have a simple addition followed by the unary positive operator.
You may argue that a line with a trailing operator is not ambiguous (and I can't currently think of a counter example), so I'll fall back on the "special cases aren't special enough to break the rules" portion of the zen of python.
Also note that the way it is now, you can join strings across multiple lines without an operator:
a = ("Hello "
"World")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With