PEP8 is the most important guide for coding standard in Python. There are also other coding practices that improve readability and maintenance.

Python coding styles and conventions

Google Python Style Guide Some highlight:

  • use pylint
  • indent: 4 spaces
  • shebang: #!/usr/bin/env python
  • comments: use pydoc format
  • naming convention
    • module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name.
    • internal variables start with underscore _

The Hitchhiker’s Guide to Python!

  • comprehensive guide on all things python

Elements of Python Style

  • slightly opiniated guide

Raymond Hettinger’s “Beyond PEP 8” from PyCon 2015 (Youtube)

This was an excellent talk regarding the python style guide and the focus on what really matters instead of just PEP8.

Summary:

  • We often miss the gorilla.
  • write an adapter class to convert
  • avoid unnecessary packaing in favor of simpler imports
  • create custom exceptions
  • use properties instead of getter/setter
  • create context manager for recurring setup and teardown logic
  • use magic methods:
    • __len__ instead of getSize()
    • __getitem__ instead of getRoutebyIndex()
    • make table iterable
  • add good __repr__ for better debuggability HN Discussion

Tools

Pylint - code analysis for Python

Using reST for docstring/pydoc

PEP 257 – Docstring Conventions

Example:

# From https://github.com/kennethreitz/requests/blob/master/requests/api.py
def get(url, params=None, **kwargs):
    """Sends a GET request.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)