When to use blank lines in a Python program?

6

Is skipping one of the aspects that make a program well-indented? If yes, what is the criteria used to skip lines?

    
asked by anonymous 25.10.2017 / 21:01

3 answers

12

Python Enhancement Proposal

These are design documents maintained by the Python community and maintained in GitHub that define guidelines for better use of language and its resources. These definitions are well argued, define a postulate and support it with the justifications of 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 essential PEPs read by the Python programmer is the eighth. PEP 8 is a code styling guide. My response was formulated on top of this PEP, which is a highly credible documentation.

In this PEP, guidelines > Python code indentation.

How many spaces to indent?

It is syntactically mandatory 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 with tabs, do EVERYTHING with tabs. The opposite is also valid. Python 3 does not even allow you to mix tabs and spaces, so you'll have:

TabError: inconsistent use of tabs and spaces in indentation

Hanging indentation lines

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

Make:

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

Do not:

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

The guideline of the four spaces 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. 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 that you should have two blank lines between the import statements 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:

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

Many recommendations are 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 .

    
25.10.2017 / 21:39
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 will comment below.

  

Surround top-level function and class definitions with two blank lines.

Fencing definitions of top-level functions and classes with two whitespaces. That is, whenever you define a new top-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
  

Whenever you define a new method in a class, leave a line 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 between multiple statements in a row. Attribution of variables, attributes in an object, lambda definitions, etc. are usually one-line structures, and in this case, the blank line can 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, in moderation, 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 quoted is completely at your discretion. In fact, these are only recommendations, you do not have to follow them. If you follow, your code will be better received by the community, as it will be much easier to understand.

    
25.10.2017 / 21:59
3

Indent is the indentation of the text in relation to its margin, that is, if before we write an instruction, we use 4 spaces from the left margin until 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: link

    
25.10.2017 / 21:09