Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no python implicit line continuation on 'and', 'or', etc.?

Tags:

python

Is there a reason why this doesn't work in Python?

if 1 != 1 or
   2 != 2:
   print 'Something is wrong...'
like image 825
user541686 Avatar asked Aug 06 '11 18:08

user541686


People also ask

How to continue code on the next line in Python?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line.

What is implicit continuation in Python?

An implicit line continuation happens whenever Python gets to the end of a line of code and sees that there's more to come because a parenthesis ( ( ), square bracket ( [ ) or curly brace ( { ) has been left open.

How to break long line in Python?

Break a long line into multiple lines using backslash According to PEP8 coding convention, each line should be limited to maximum 79 characters for better readability.


2 Answers

Perhaps this prevents a grammar ambiguity, but I feel that this behaviour is in the spirit of PEP 20, specifically 'Simple is better than complex' (among others). In other words, 'Unless you have a good reason, why should expressions span multiple lines?'. If you have a good reason, the syntax devices to get around this are provided.

[edit] I did some more reading, and there are a few references of interest:

  • The lexical definition of statements says that logical lines end in with a newline. Each case for adding an implicit continuation becomes and exceptional case.
  • PEP 3125 for Python 3, proposed removing slash (\) continuation, but was rejected due to lack of support.
    • Discussion in the mailing list reminds us that parenthetical continuation occurs because newlines do not end statements while parenthesis remain unbalanced.
    • In that same thread, Guido opposes the change because errors like the following are disguised:

    x = y+    # Used to be y+1, the 1 got dropped
    f(x)

My final point is, the slash acts (or open parens) acts as a reminder that the statement is continued on the next line. Depending on your indentation, it's possible that the continuation could be mistaken for a separate statement (which I think this other response touches on).

like image 54
Dana the Sane Avatar answered Oct 07 '22 14:10

Dana the Sane


Implicit line continuation only happens in Python if parentheses, brackets, or braces are open. Put parentheses around your condition and it will work.

like image 39
kindall Avatar answered Oct 07 '22 14:10

kindall