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?
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.
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.
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.
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.
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()
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