Python Coding Standards

↗ Coding standards (style guide) for Python programs, by AmitDiwan

Naming Conventions

The following are the currently recommended naming standard.

Avoid These Names

Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names. Package and Module Names

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Name of Class

Class names should normally use the CapWords convention. The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable.

Exception Names

The class naming convention applies here. However, you should use the suffix “Error” on your exception names.

Function and Variable Names

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

Function and Method Arguments

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

Method Names and Instance Variables

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

Use one leading underscore only for non-public methods and instance variables.

To avoid name clashes with subclasses, use two leading underscores to invoke Python’s name mangling rules.

Constants

Constants are usually defined on a module level and written in all capital letters with underscores separating words.

Indentation

The guideline suggests using 4 spaces per indentation level.

Tabs or Spaces

Tabs should be used solely to remain consistent with code that is already indented with tabs.

Python disallows mixing tabs and spaces for indentation.

Maximum Line Length

Limit all lines to a maximum of 79 characters.

Imports

The import statement, just like any other statement or keyword in Python should be used and added to the code properly following the best practices. Let’s see them one by on −

Multiple Imports

Multiple Imports should usually be on separate lines. For example −

import numpy
import pandas
import matplotlib

Always on the Top

Imports are always put at the top of the file i.e.

  • After any module comments and docstrings.
  • Before module globals and constants.

For example −

# import the numpy module
import numpy

Import Modules in an Order

A good practice is to import modules in the following order −

  • Standard library modules – e.g. sys, os, getopt, re.
  • Third-party library modules – e.g. ZODB, PIL.Image, etc.
  • Locally developed modules.

Absolute Imports

Absolute imports are recommended, as they are usually more readable and tend to be better performed if the import system is incorrectly configured. For example −

import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

Wildcard imports (from import *) should be avoided

Avoid the Wildcard imports since they make it unclear which names are present in the namespace, confusing both readers and many automated tools.

Whitespace in Expressions and Statements

Avoid unnecessary whitespace as in the following situations −

Between a trailing comma:

# Correct:
a = (0,)

# Wrong:
b = (0, )

Immediately before a comma, semicolon, or colon −

# Correct:
if a == 5: print(a, b); a, b = b, a

# Wrong:
if a == 5 : print(a , b) ; a , b = b , a

Immediately before the open parenthesis that starts the argument list of a function call

# Correct:
demo()

# Wrong:
demo ()

Immediately before the open parenthesis that starts an indexing or slicing

# Correct:
dct['key'] = lst[index]

# Wrong:
dct ['key'] = lst [index]

Comments

  • Comments should be complete sentences.
  • The first word should be capitalized, unless it is an identifier that begins with a lower case letter.
  • Block comments generally consist of one or more paragraphs built out of complete sentences, with each sentence ending in a period.
  • You should use two spaces after a sentence-ending period in multi- sentence comments, except after the final sentence.

Folder Structure

https://forum.djangoproject.com/t/unclear-about-folder-structure-with-virtual-environment/11447https://stackoverflow.com/questions/193161/what-is-the-best-project-structure-for-a-python-application

Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple.

/scripts or /bin for that kind of command-line interface stuff
/tests for your tests
/lib for your C-language libraries
/doc for most documentation
/apidoc for the Epydoc-generated API docs.

And the top-level directory can contain README's, Config's and whatnot.

The hard choice is whether or not to use a /src tree. Python doesn't have a distinction between /src, /lib, and /bin like Java or C has.

Since a top-level /src directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.

/foo
/bar
/baz

I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named quux, the directory that contains all this stuff is named /quux.

Another project's PYTHONPATH, then, can include /path/to/quux/foo to reuse the QUUX.foo module.

In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level /quux directory, and omit adding it to SVN.

Project/
|-- bin/
|   |-- project
|
|-- project/
|   |-- test/
|   |   |-- init.py
|   |   |-- test_main.py
|   |   
|   |-- init.py
|   |-- main.py
|
|-- setup.py
|-- README