Skip to content

Instantly share code, notes, and snippets.

@rmariano
Last active May 16, 2017 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmariano/4f57be7966d939e56716 to your computer and use it in GitHub Desktop.
Save rmariano/4f57be7966d939e56716 to your computer and use it in GitHub Desktop.
Coding guildelines for Python

Coding style

This file should summarize some important points to take into account in order to achieve a clean code base, enumerating not only style traits but also tips that might make the code more readable and maintainable.

1. PEP8 with criteria: for example if a line goes beyond 80 cols, but breaking it would make an ugly code, or if the exceeding part is trivial (a comma, brackets, etc.), then leave it as it is, do not make pointless trims.

2. Use identifiers (for example functions/classes) for separating concerns Some people argue that functions are for reusing code (if that code is to be called multiple times), and then and only then a function should be used. I disagree.

  • Even if the code is called only once, but is doing a completely different thing, use a function.
  • If the code has to be encapsulated, use a function.
  • If the code performs some action on its own, and its behaviour is not clear nor declarative, use a function.
  • If you are using a comment to explain some lines of code, use a function and remove the comment!.

    For example:

    if x * y < 0:
        rest_of_the_code()

Why are we asking if the product of x and y is negative? Even if this is obvious, is not documented. The readable alternative would be:

def have_different_sign(x, y):
    return x * y < 0

if have_different_sign(x, y):
    rest_of_the_code()

Much more readable, and intention revealing.

3. High cohesion, low coupling.

3.1 Functions should be small 3.2 Functions should do one thing. They should do it only. They should do it well.

  1. Docstrings in every function, class, and module. Comply with PEP257.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment