When to use blank lines in a Python program?

Asked

Viewed 1,500 times

7

Skipping lines is one of the aspects that make a program well indented? If so, what is the criteria used to skip lines?

  • Too many blank lines make the code unreadable. And too few blank lines

3 answers

13


Python Enhancement Proposal

These are design documents maintained by the Python community and maintained on Github defining guidelines for better use of language and its resources. These definitions are well argued, define a postulate and support it with the justifications for the adoption of this document. They are numbered, so it is common to read PEP 1, PEP 5, PEP 8 or PEP 500.

One of the Peps said essential reading from the Python programmer is the eighth. A PEP 8 is a code stylization guide. My answer has been formulated upon this PEP, which is a highly credible documentation.

This PEP also defined guidelines indentation of Python code.

How many spaces to indent?

It is syntactically required that you indent your Python code. PEP tells you to use four spaces per indentation level.

print("olá")
if foo:
    # quatro espaços

Tabs and/or spaces

Spaces are preferable. Be consistent: if you do tabs, do EVERYTHING with tabs. The opposite is also valid. Python 3 doesn’t even allow you to mix tabs and spaces, so you’ll have:

TabError: inconsistent use of tabs and spaces in indentation

Code continuation lines (Hanging indentation)

Hanging indentation is when all paragraph lines are indented except the first.

Do:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

Don’t do:

# Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

The four-space Guideline is optional in this type of indentation. You can do:

foo = long_function_name(
  var_one, var_two,
  var_three, var_four)

Limit any line of code to 79 characters. For where there is no way, use the escape character like this:

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

Line breaks

PEP 8 says you should have two blank lines between the statements of import and the rest of the code.

import x
import y
import z


def foo()
    pass

And two breaks between each defined function.

def a()
    pass


def b()
    pass

Another PEP that says about line breaks is PEP 257, which defines Python code documentation conventions. There it says:

There’s no Blank line either before or after the docstring.

So do this thing:

def alo():
    """Retorna um alô"""
    return 'alô'

There are many recommendations defined in this PEP. There is a tool to check if your code is within PEP 8, based on pep8.py. See PEP8 online check.

6

Python has a style guide that is widely used by the community and there is a section on blank lines in the code: PEP 8 -- Style Guide for Python Code: Blank Lines. Below I will quote the original text, in English, and comment soon below.

Surround top-level Function and class Definitions with two Blank Lines.

Surround definitions of upper-level functions and classes with two blank spaces. That is, whenever defining a new upper-level function or a class, leave a two-line spacing.

import json


def stringify(obj):
    return json.loads(obj)


def show(string):
    print(string)


class Person:

    def __init__(self, name):
        self.name = name

Method Definitions Inside a class are surrounded by a single Blank line.

Whenever defining a new method in a class, leave a row spacing around it.

class Person:

    def __init__(self, name):
        self.name = name

    def walk(distance):
        ...

    def speak(text):
        ...

Extra Blank Lines may be used (sparingly) to Separate groups of Related functions. Blank Lines may be omitted between a Bunch of Related one-Liners (e.g. a set of dummy implementations).

Blank lines can be used (sparingly) to separate groups of related functions and can be omitted from several statements of a line. Variable assignment, attributes on an object, structure definitions Amble, etc, are usually structures of a line and in this case the blank line may be omitted.

x = 1
y = 2
z = 3

distance = lambda x, y, z: x + y + z
square = lambda x: x**2

Use Blank Lines in functions, sparingly, to indicate Logical sections.

Use blank lines in functions, sparingly, to separate logical sections. For example, variable assignment, validation, etc.

def status(age):

    output = "baby"  # atribuição

    if age < 0:  # validação
        raise Exception("The age must be a non-negative number")

    if 2 < age < 18:  # lógica
        output = "young"
    elif age < 60:
        output = "adult"
    else:
        output = "old"

    return output  # retorno

In any other case not cited is entirely up to you. Actually, these are just recommendations, you don’t have to follow them. If you follow, your code will be better received by the community, as it will be much easier to understand it.

3

Indenting is the indentation of the text in relation to its margin, that is, if before writing an instruction, we use 4 spacing from the left margin to the instruction itself, we can say that the indentation used has 4 spaces.

#coding: utf-8

print(nivel 1)#primeiro nível hierárquico

if(True):
    print(nível 2)#segundo nível hierárquico

More information: http://excript.com/python/indentacao-python.html

  • 2

    And about skipping lines?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.