Python coding standards

Indentation is rigidly enforced in python.  Python script does not run if the indentation is not followed. Entire block of code should come under single indentation. (should have same number of spaces or tabs).

Pylint software:

Pylint is a tool that checks for errors in python code. It checks for coding conventions,  lines and indentation, etc. For example it checks for:

  1. Checks if there are unused imports.
  2. Unused variables assigned.
  3. Checks if the declared interfaces are fully implemented etc.

PEP8 coding standards:

High level of readability is one of the most important features of python. PEP8 standards provide guidelines to improve readability of code and make it consistent on wide variety of python scripts. Example:

  1. Indentation: 4 spaces for indentation.
  2. Spaces are a preferred indentation method.
  3. Limits all the lines to a maximum of 79 characters.
  4. Method definitions in a class are separated by a blank line.
  5. Imports : Imports should always be on separate lines. Imports should be grouped in the following order:
  • standard library imports
  • related third party imports
  • local application/library specific imports
  1. Avoid white space in the following situations:

Immediately inside parentheses, brackets or braces.

Yes: spam(apple[1], {mango: 2})
No: spam( apple[ 1 ], { mango: 2 } )

Immediately before a comma, semicolon, or colon:

Yes: if x == 4: print x, y; x, y = y, x
No: if x == 4 : print x , y ; x , y = y , x

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

Yes: spam(1)
No: spam (1)

Immediately before the open parenthesis that starts an indexing or slicing:

Yes: dict['key'] = list[index]
No: dict ['key'] = list [index]

Immediately before the open parenthesis that starts an indexing or slicing:

x = 1
y = 2
long_variable = 3
x    = 1
y    = 2
long_variable    = 3

Other recommendations:

Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).


Use inline comments sparingly.

x = x + 1 # Increment x

 A tool that automatically formats Python code to conform to the PEP 8 style guide.

To run autopep8:

$ autopep8


One thought on “Python coding standards

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s