Split long conditional expressions to lines

kbec picture kbec · Jul 30, 2012 · Viewed 14.8k times · Source

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?

Answer

Kos picture Kos · Jul 30, 2012

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