Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split long conditional expressions to lines

Tags:

I have some if statements like:

def is_valid(self):     if (self.expires is None or datetime.now() < self.expires)     and (self.remains is None or self.remains > 0):         return True     return False 

When I type this expressions my Vim automatically moves and to new line with this same indent as if line . I try more indent combinations, but validating always says thats invalid syntax. How to build long if's?

like image 765
kbec Avatar asked Jul 30 '12 13:07

kbec


People also ask

How do I split a code into multiple lines?

To break a single statement into multiple linesUse the line-continuation character, which is an underscore ( _ ), at the point at which you want the line to break.

How do you break a long condition in Python?

The recommended style for multiline if statements in Python is to use parenthesis to break up the if statement. The PEP8 style guide recommends the use of parenthesis over backslashes and putting line breaks after the boolean and and or operators.

How do you handle long IF statements in Python?

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

What if the line is too long in Python?

If you have a very long line of code in Python and you'd like to break it up over over multiple lines, if you're inside parentheses, square brackets, or curly braces you can put line breaks wherever you'd like because Python allows for implicit line continuation.


1 Answers

Add an additional level of brackets around the whole condition. This will allow you to insert line breaks as you wish.

if (1+1==2   and 2 < 5 < 7   and 2 != 3):     print 'yay' 

Regarding the actual number of spaces to use, the Python Style Guide doesn't mandate anything but gives some ideas:

# No extra indentation. if (this_is_one_thing and     that_is_another_thing):     do_something()  # Add a comment, which will provide some distinction in editors # supporting syntax highlighting. if (this_is_one_thing and     that_is_another_thing):     # Since both conditions are true, we can frobnicate.     do_something()  # Add some extra indentation on the conditional continuation line. if (this_is_one_thing         and that_is_another_thing):     do_something() 
like image 112
Kos Avatar answered Oct 21 '22 11:10

Kos