Should if statements be surrounded by blank lines to follow PEP8?

Viewed 6336

I've read the blank line section in pep8. It says that we should surround top level functions with blank lines, but it doesn't say anything about if statements.

I've done some digging on what a top level is in Python and it seems to be anything that's not indented. Does this mean that if statements should be surrounded by blank lines? Are if statements considered functions?

I can't find anything on stack overflow about this.

1 Answers
"""
my cool and interesting program!
"""

import this_module
import that_module
import another_module


def procedure_to_do_this(*args):
    if args:
        print("the caller says %s!" % args[0])
    elif not args:
        print("the caller is too shy to say anything ;c")
    else:
        print("if you've reached this point, there's no turning back")

    return something


procedure_to_do_this()

Is how you'd typically form an if/elif/else structure, however at most times it is subjective to you whether that structure complies with the rest of the code or not, of course you can change it around if you feel there's too much code inside one of the conditional clauses and that you want to distinguish the conditionals, you can put an extra newline after the end of one conditional e.g.:

if this:
    <a lot of code>
    <a lot of nice code>
    <a lot of long code>
<newline>
elif that:
    <a lot of other code>

et cetera.

Always keep in mind that PEP8 is simple a styling guide[line], it by no means is to dictate the over-all design of your code because it is subjective itself to what people thought good styling looked when there was good or specific code there.

Not all code looks good in a certain style, so that's why it's a guideline and not something that Python strictly enforces and has implemented into the intepreter.

Related