Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when is a python operator a line continuation?

Tags:

python

syntax

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.

like image 981
aestrivex Avatar asked Mar 27 '13 17:03

aestrivex


2 Answers

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.

like image 99
Gareth Latty Avatar answered Sep 20 '22 07:09

Gareth Latty


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")
like image 42
mgilson Avatar answered Sep 18 '22 07:09

mgilson