Python Common Style Guidelines

One of the best practices is, to define a common style guideline. So that it would be much easier to understand a codebase when all the code in it, is in a consistent style. Specially if you are working in a team. PEP (Python Enhancement Proposals) provides a good starting point to define those style guide.

Here are some highlights which are mostly from PEP 8, but also from other best practices:

Naming Conventions

Avoid one letter variables like x and y (Except in very short code blocks). Give your variables and functions a meaningful name and use follow naming convention:

  • Variables, functions, packages and modules names should be:

    1
    lower_case_with_underscores
  • Classes and Exceptions

    1
    CamelCase
  • Protected methods

    1
    _single_leading_underscore
  • Private methods

    1
    __double_leading_underscore
  • Constants

    1
    ALL_CAPS_WITH_UNDERSCORES

Programming Recommendations

  • Comparisons to singletons like None should always be done with is or is not, never the equality operators.

    1
    2
    3
    if user is None:  # Use that

    if user == None # Don't use that
  • For sequences, (strings, lists, tuples), use the fact that empty sequences are false. Don’t use the len() function.

    1
    2
    3
    4
    5
    if not seq:           # Use that
    if seq: # Use that

    if len(seq): # Don't use that
    if not len(seq): # Don't use that
  • Don’t compare boolean values to True or False using ==

    1
    2
    if greeting:          # Use that
    if greeting == True: # Don't use that

Indentation

Use spaces, instead of tabs (your IDE can probably convert tabs automatically to spaces). Taking 2 or 4 spaces are both fine. Just agree a convention in your team. Never mix the indentations.

Imports

Put all imports at the top of the file with three sections, each separated by a blank line, in this order:

  • System imports
  • Third-party imports
  • Local source tree imports

That makes it clear where each module is coming from. Also Imports itself should usually be on separate lines.

Pylint

Pylint is a Python static code analysis tool which looks for programming errors and help to enforce the rules of PEP 8. Most of the IDE’s have an integration of pylint. Personally I use the TensorFlow code style guide, which is based on PEP 8 and Google Python Style Guide. Just download the pylintrc file, which contains all the rules, from e.g. TensorFlow and point your pylint to that file.