Coding Standards: Python Code

The Python coding standards used here are based on the standard Python coding standards, known as “PEP 8”. The following are notable deviations from or clarifications of the standard:

  • Line length — While we try to keep lines to the prescribed maximum of 79 characters, this is frequently exceeded, especially when a line contains an SQL query or literal string.
  • We usually use relative imports for importing other parts of the system.
  • Parentheses — We put a space outside of parentheses, unless they are immediately inside an outer set of parentheses. In particular, a space separates the called function from its parameters. For example:

    function_name ((a * b) + (c * d))

    In addition, more space is preferred in expressions, particularly to make the structure more clear.

  • String Quotes — We always use curly quotes (“ ”) for running text, so the occurrence of single quotes (' ') and double quotes (" ") is generally rare. In terms of choosing when to use single quotes or double quotes, there are two main situations: using them in HTML generating code, and using them in SQL queries.

    In HTML generating code, single quotes are used for text/element content of the page, while double quotes are used for attributes. This includes components of HTML, values that end up being HTML, and values that result from HTML.

    For example, in ll.xist, the library we use to generate HTML, we write the following expression:

    html.p ('Here is a sample link to ', html.a ('an example site', href="http://example.com"), '.')

    to generate the following HTML expression:

    <p>Here is a sample link to <a href="http://example.com">an example site</a>.</p>

    Hence, the attributes are used in double quotes in both the actual HTML as well as the HTML source, while single quotes are used for the text/element content.

    In SQL queries, double quotes are always used. In SQL, strings use single quotes and as SQL queries may need to mention a literal string, it works well to use double quotes for a Python string that contains the SQL query. Double quotes are used nonetheless in SQL queries and query fragments that do not contain SQL literals.

Docstrings are used to document the code and produce Sphinx pages. We use the Docstring Conventions, known as “PEP 257”, as a starting point. More details are available on a separate page.