Skip to content

Instantly share code, notes, and snippets.

@tomschr
Last active May 13, 2024 02:13
Show Gist options
  • Save tomschr/c23585f6bcbeb6374f183deb83352f36 to your computer and use it in GitHub Desktop.
Save tomschr/c23585f6bcbeb6374f183deb83352f36 to your computer and use it in GitHub Desktop.
Python Checklist for Clean Code

Programming Checklist for Clean Code in Python

This checklist contains some tips and recommendations sorted into a syntax and a design category.

It should help to overcome common pitfalls.

Syntax

  1. Check your header of your file. It should contain:

    a. Shebang line #!/usr/bin/env python3 if it's a script. Leave it out if you have a module or a package.

    b. File docstring about the purpose of this file.

    c. If needed, a list of imports; every import should occupy one line. Use isort to keep them sorted.

    d. Meta information like __author__, __version__, and __url__.

    e. If needed, global constants in uppercase letters.

  2. Check if all your functions contain a docstring with the following properties:

    a. First line with the purpose of the function.

    b. Empty line.

    c. One or more lines describing the arguments.

    d. A line describing possible return values.

    e. A line describing possible exceptions.

  3. Keep your source code tidy. Why? Because, good looking source code is easier to read and maintain.

  4. Follow PEP8. Use black or other source code formatters.

  5. If you write a script, add a if ___name__ == "__main__" line at the end. This is needed to distinguish between a module and a script.

  6. Be pythonic. That's a broad topic, but usually pythonic code is clear code.

  7. Try to follow a naming convention for your variables:

    a. Use uppercase letters for global constants.

    b. Use an uppercase letter as first letter for classes.

    c. Use lowercase letters for all other variables.

    d. Use an underscore to indicate that a variable is "private".

Design

  1. Import only those modules or packages that you really need.

  2. Restrict your imports to only the functions and classes that you really need.

  3. Make sure that every of your functions fullfil only one purpose.

  4. Write "simple" functions.

  5. Try to limit the complexity of your code. Install the packages python3-mccabe and python3-flake8 and run:

    $ flake8 --max-complexity 8 my_script.py
    

    It gives you a list of functions that may be "complex", so it maybe a hint to try to make such functions simpler.

  6. Use meaningful names for your function, classes, and variables:

    a. Be as specific as possible.

    b. Use nouns for classes and verbs for methods.

    c. Use only common names for temporary variables like i, j, k, m, n for integers and c, d, and e, for characters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment