allow line break at operators

Chris Angelico rosuav at gmail.com
Wed Aug 10 17:13:42 CEST 2011


On Wed, Aug 10, 2011 at 3:37 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
>> Without the parentheses, this is legal but (probably) useless; it
>> applies the unary + operator to the return value of those functions.
>> Putting the + at the end of the previous line at least prevents that,
>> since most unary operators bind to the operand on the right;
>
> Not so:
>
>>>> x = (42 + -
> ...     100)
>>>>
>>>> x
> -58

Your unary - is binding to the operand to its right, in this case the
100. (I think I have left and right correct; being in theatre has a
tendency to make you forget which is which.) Your + is binary,
operating on 42 and the result of applying unary - to 100, which is
-100.

My point about binding can be illustrated by inventing an operator @.
Let's say that a at b is the atan2 of a and b, and x@ is x factorial (I
can't imagine what deranged mind would do something like this, apart
from my own).

y = 5 @     # 120, as per factorial
x = 5 @ 2   # 1.19 or so, as per atan2
foo(123)     # Calls foo() and discards its return value
z = 5 @
foo(123)

Is that last example one statement or two?

But this situation shouldn't ever occur in Python, because all its
unary operators (not, -, +, ~) bind to the operand to their right (I
don't think there's any I've missed, are there?). It does mean,
however, that a leading operator is not unambiguous. Without the
surrounding parentheses and/or otherwise-unexpected indentation, an
expression beginning with a + could conceivably be applying the unary
plus operator to the rest of the expression, rather than implying that
it's continuing the previous line.

Chris Angelico



More information about the Python-list mailing list