Lab Style Guide: Python

Python Style Guide
==================

For readability and maintainability, it’s critical to use a consistent coding style. The coding rules described in this document will help ensure that consistency.

Organization
————

Organize your computer code like you would a scientific paper.

1. The largest unit of organization in a paper is the section (e.g., the “Results” section, the “Discussion” section, etc.).
* In code, a “section” is comprised of all program elements that share the same general purpose (e.g., string manipulation, user input, etc.).
* __Each code section should be saved in a separate file.__ Organize your files in subdirectories to reflect the hierarchical organization of your code. In Python, that means using [packages](https://docs.python.org/3/tutorial/modules.html#packages).
2. In a scientific paper, sections are divided into subsections.
* In code, each class or definition in a given file is equivalent to a subsection.
* Typically there will be one class in each file, though in some cases multiple classes/definitions per file may be appropriate.
3. In scientific writing, subsections are divided into paragraphs.
* In code, each of the definitions within a class are like a paragraph.
* Like a paragraph, the code in each definition should be focused on a single task (like a topic sentence).
4. Paragraphs are made of sentences.
* In code, a “sentence” is a few commands that perform the same subtask.
* It’s not necessary to comment every line, but it is best to include a brief comment at the beginning of each code “sentence.”

Here’s an example in meta code:

“`
File (“section”): StringDefinitions.code
Class (“subsection”): Capitalization
Definition (“paragraph”): TitleCase
“Sentence” 1:
# Comment: Make all the letters lower case.
make_letters_lower_case_commands

“Sentence” 2:
# Comment: Make the first letter capital case.
make_first_letter_capital_commands
“`

White Space
———–

1. __Tabs__ aren’t allowed. Instead, use four spaces.
2. __Blank lines__ are useful for separating different code sections.
* All code should end in a single blank line.
* Two blank lines should precede every class definition, as well as any top-level definition (not contained in a class). Otherwise, two consecutive blank lines are not allowed.
3. __Spaces__
* Lines can’t end in spaces.
* A space should follow every comma.
1. Wrong: `(“a”,”b”)`
2. Right: `(“a”, “b”)`
* Parentheses and square brackets aren’t padded with spaces.
1. Wrong: `( “a”, “b” )` `[ “a”, “b” ]`
2. Right: `(“a”, “b”)` `[“a”, “b”]`
* Certain characters must be flanked by spaces: + – < > =
1. Wrong: `5+3=8` `5>3-1` `3<5` 2. Right: `5 + 3 = 8` `5 > 3 – 1` `3 < 5` Line Lengths ------------ 1. No line can be longer than 79 characters. Parentheses can often be used to split lines: ```python if (not line.startswith("var ") and not line.startswith("function ") and not line.startswith("window ") and not line.startswith("/*") and not line.startswith("*")): name = line.replace("(", " ") name = name.replace("=", " ") name = name.replace(":", " ").split()[0] ``` Functions and Variables ----------------------- 1. Function and variable __names__. * In python, functions are named_like_this(). * Classes are named in TitleCase. 2. All classes and functions must have __docstrings__. Class docstrings look like this: ```python class PythonChecker(Checker): """A class for checking python styling.""" ``` Definition docstrings look like this: ```python def recursive_file_search(dirname, file_mask, exclude_strings = []): """A directory to resursively search for a file. Args: dirname (string): The directory. Can also be a file. file_mask (string): The file mask (e.g., *.py). exclude_strings ([string]): Optional. Any files containing these strings will be ignored. Defaults to []. Returns: [string]: A list of the matching files. """ ``` Miscellaneous ------------- No script should run anything when imported. So unless your code is in a class or definition, place it in a conditional like this: ```python if __name__ == "__main__": # Python code here. ```