.. _styleguide:

Coding Style
------------

*Inspired by Django's Styleguide*

Please follow these coding standards when writing code for inclusion in Protean.

.. _coding-style-python:

Python style
============

* Please conform to the indentation style dictated in the ``.editorconfig``
  file. We recommend using a text editor with |editorconfig| support to avoid
  indentation and whitespace issues. The Python files use 4 spaces for
  indentation.

* Unless otherwise specified, follow :pep:`8`.

  Use |flake8| to check for problems in this area. Note that our ``setup.cfg``
  file contains some excluded files as well as some excluded errors that we don't
  consider as gross violations. Remember that :pep:`8` is only a guide,
  so respect the style of the surrounding code as a primary goal.

  An exception to :pep:`8` is our rules on line lengths. Don't limit lines of
  code to 79 characters if it means the code looks significantly uglier or is
  harder to read. We allow up to 119 characters as this is the width of GitHub
  code review; anything longer requires horizontal scrolling which makes review
  more difficult. This check is included when you run ``flake8``. Documentation,
  comments, and docstrings should be wrapped at 79 characters, even though
  :pep:`8` suggests 72.

* Use four spaces for indentation.

* Use four space hanging indentation rather than vertical alignment::

    raise AttributeError(
        'Here is a multiline error message '
        'shortened for clarity.'
    )

  Instead of::

      raise AttributeError('Here is a multiline error message '
                           'shortened for clarity.')

  This makes better use of space and avoids having to realign strings if the
  length of the first line changes.

* Use single quotes for strings, or a double quote if the string contains a
  single quote.

* Avoid use of "we" in comments, e.g. "Loop over" rather than "We loop over".

* Use underscores, not camelCase, for variable, function and method names
  (i.e. ``poll.get_unique_voters()``, not ``poll.getUniqueVoters()``).

* Use ``InitialCaps`` for class names (or for factory functions that
  return classes).

* In docstrings, follow the style of existing docstrings and :pep:`257`.

.. _coding-style-imports:

Imports
=======

* Use `isort <https://github.com/timothycrosley/isort#readme>`_ to automate
  import sorting using the guidelines below.

  Quick start:

  .. code-block:: none

      $ pip install isort
      $ isort -rc .

  This runs ``isort`` recursively from your current directory, modifying any
  files that don't conform to the guidelines. If you need to have imports out
  of order (to avoid a circular import, for example) use a comment like this::

      import module  # isort:skip

* Put imports in these groups: future, standard library, third-party libraries,
  other Protean components, local Protean component, try/excepts. Sort lines in
  each group alphabetically by the full module name. Place all ``import module``
  statements before ``from module import objects`` in each section. Use absolute
  imports for other Protean components and relative imports for local components.

* On each line, alphabetize the items with the upper case items grouped before
  the lowercase items.

* Break long lines using parentheses and indent continuation lines by 4 spaces.
  Include a trailing comma after the last import and put the closing
  parenthesis on its own line.

  Use a single blank line between the last import and any module level code,
  and use two blank lines above the first function or class.

  For example (comments are for explanatory purposes only):

  .. code-block:: python
      :caption: protean/utils/example.py

      # future
      from __future__ import unicode_literals

      # standard library
      import json
      from itertools import chain

      # third-party
      import bcrypt

      # Protean
      from protean.core.entity import Entity
      from protean.core.transport import (
          RequestObject, ResponseSuccess
      )

      # local Protean
      from .models import Account

      # try/except
      try:
          import yaml
      except ImportError:
          yaml = None

      CONSTANT = 'foo'


      class Example:
          # ...

* Use convenience imports whenever available. For example, do this::

      from protean.transport import RequestObject

  instead of::

      from protean.transport.request import RequestObject

Entity style
============

* Field names should be all lowercase, using underscores instead of
  camelCase.

  Do this::

      class Person(Entity):
          first_name = field.String(max_length=20)
          last_name = field.String(max_length=40)

  Don't do this::

      class Person(Entity):
          FirstName = field.String(max_length=20)
          Last_Name = field.String(max_length=40)

* The ``class Meta`` should appear *after* the fields are defined, with
  a single blank line separating the fields and the class definition.

  Do this::

      class Person(Entity):
          first_name = field.String(max_length=20)
          last_name = field.String(max_length=40)

          class Meta:
              abstract = True

  Don't do this::

      class Person(Entity):
          first_name = field.String(max_length=20)
          last_name = field.String(max_length=40)
          class Meta:
              abstract = True

  Don't do this, either::

      class Person(Entity):
          class Meta:
              abstract = True
          first_name = field.String(max_length=20)
          last_name = field.String(max_length=40)

* The order of entity inner classes and standard methods should be as
  follows (noting that these are not all required):

  * All fields
  * ``class Meta``
  * ``def __str__()``
  * ``def save()``
  * Any custom methods

Miscellaneous
=============

* Remove ``import`` statements that are no longer used when you change code.
  |flake8| will identify these imports for you. If an unused import needs to
  remain for backwards-compatibility, mark the end of with ``# NOQA`` to
  silence the flake8 warning.

* Systematically remove all trailing whitespaces from your code as those
  add unnecessary bytes, add visual clutter to the patches and can also
  occasionally cause unnecessary merge conflicts. Some IDE's can be
  configured to automatically remove them and most VCS tools can be set to
  highlight them in diff outputs.

* Please don't put your name in the code you contribute. Our policy is to
  keep contributors' names in the ``AUTHORS`` file distributed with Protean
  -- not scattered throughout the codebase itself. Feel free to include a
  change to the ``AUTHORS`` file in your patch if you make more than a
  single trivial change.

.. |editorconfig| raw:: html

    <a href="https://editorconfig.org/" target="_blank">EditorConfig</a>

.. |flake8| raw:: html

    <a href="https://pypi.org/project/flake8/" target="_blank">Flake8</a>
