Python Coding Conventions and Standards
The following coding conventions and standards apply to all work in MF602. You should always follow these standards, and adherance will be rewarded in the grading.
Note: this is a summary of the rules found in PEP 8, the official style guide for Python code, written by the authors of the Python language.
Header Comments
You must begin each file with a brief header comment, which must include the following elements: The file name Your name, BU email, and the date you created the file * A brief description of the work contained in the file.
For example:
# File: hello_world.py # Author: Aaron Stevens (azs@bu.edu), 3/24/2006 # Description: Our first Python program, in which we demonstrate # writing output to the console window.
Comments
Comments should help the reader of your code to understand it. They may help you to understand it if you need to rework your code at some later point. In the case of a program submitted for this course, they also serve to convince the grader that you grasp the what, how and why of your code (as opposed to having hacked it into working). In particular, please observe the following guidelines:
-
For each significant variable declaration, give a brief comment stating the use of the variable, and when useful, the units (e.g., feet or inches). Non-significant variables (not requiring explanation) would include temporary variables, loop counters, and so on.
-
When it helps to understand your code, before each major section of the program, give the purpose of that section.
-
Indent the comments to line up with the code.
-
Before every control structure (e.g., if/else statement, loop), explain why this control structure is necessary/what it is doing.
Documentation strings
Documentation strings (or docstrings) can be attached to any module
(at the top of the .py
file), function (after the def
line), or class
(after the class
line). They are simple strings that are better than
surrounding comments, since they can be reviewed using Python’s help()
function, among other uses. (More information is available in PEP
257, Docstring Conventions.)
Use the triple-double quotation marks ("""
) to start and end a
docstring. The docstring should begin on the line with the opening
"""
, as follows:
def factorial(n): """Return the factorial of n."""
If the docstring can’t fit on one line, move the ending """
to its
own line after the string and keep writing the docstring. Do not add
an extra newline after the opening """
. For example:
def replace(secret_word, display_word, letter): """Return a list of characters that results from taking the existing display word list and revealing any and all occurrences of the specified letter, as dictated by secret_word. """
Another point to note: PEP 257 states that function docstrings should be a phrase ending with a period that describes the effect of the function as a command, rather than describing it (see the examples above).
Variable and Function Names
Choose your names carefully. As part of program documentation, names must
clearly indicate both the kind of thing being named and its role in the
program. Whenever possible, write short, obvious names for very local contexts
(i.e., a for
loop counter could be called i
) and longer names for bigger
contexts (examples to follow). Avoid cryptic abbreviations (e.g., use
increment_event_count()
rather than incevcnt()
). Avoid choosing similar
names for different things (e.g., index
, indx
, index2
), or, on the other
hand, similar names for very different things (example: if keys
is a list of
strings, then don’t use key
for an integer).
- attribute and local variable names should be noun phrases, written in
lowercase, with multiple words distinguished by a single underscore (
_
) - function names (and method names) should be imperative verb phrases
(if possible), lowercase, with words separated by underscores (e.g.,
get_student_name()
) - modules should have short, lowercase names, with underscores if necessary
- class names should have capitalized words, without underscores to
separate each word (e.g.,
ClassName
) - variables or attributes that should be considered unchanging (i.e., “constants” in other languages like Java) should be written in all capital letters with underscores separating words
Indentation
Python uses indentation to manage the visiblity and scope of statements in your code. You must use the correct indentation to create code that is syntactically correct.
Spyder is a software program that makes it easier to write and run Python code. We will use Spyder extensively in this course when we write programs, since it provides text editor features like code highlighting and automatic indentation.
In an Spyder Editor window, pressing the tab key will cause Spyder to increase the indent level. By default, Spyder will insert the appropriate number of ASCII space characters to get the text cursor to the next level of indentation.
In other text editors, pressing the tab key might insert a tab character (a special character indicating an indent). This is not ideal — if you aren’t using Spyder, you should configure your editor to use spaces.
Whitespace
Using blank lines
While the horizontal position of code on a line (i.e., indentation) conveys important information to the Python interpreter, the interpreter ignores the vertical spacing of code in a file. For example, this function definition
def distance(yards): print("yards: " + str(yards)) feet = yards * 3 print("feet: " + str(feet)) inches = feet * 12 print("inches: " + str(inches)) return inches
is equivalent to this one:
def distance(yards): print("yards: " + str(yards)) feet = yards * 3 print("feet: " + str(feet)) inches = feet * 12 print("inches: " + str(inches)) return inches
However, the second definition* is more readable. Therefore putting blank lines between logical sections of code is encouraged, to increase readability.
Spaces in between elements on a line
The Python interpreter also ignores the spaces between binary operators
like =
or +
. Therefore the expressions a=b
and a = b
are
equivalent. You should get into the habit of using a single space
between the operands in these expressions. However, a couple of notable
exceptions to this whitespace rule can be found below:
-
Avoid spacing inside parentheses. For example, prefer
convert(15.2, "inches", "miles")
overconvert( 15.2, "inches", "miles" )
. -
Avoid spacing between a function name and the parameter list. For example, prefer
hello("Cody")
overhello ("Cody")
. -
Avoid spacing before a comma or colon. For example, prefer this
if x == 4: a, b = x, y; x, y = y, x
over the more confusing version:
if x == 4 : a, b = x , y ; x , y = y , x
-
Avoid spacing before indexing a dictionary. For example, prefer
dict['key']
overdict ['key']
.
Miscellaneous
-
Keep line lengths under 80 characters. On many machines and in many software packages, this is a standard line length. It makes it easier for others (like graders) to read and/or print your programs. If your parameter list for a function or method is too long to fit within 80 characters, then insert line breaks and indent the remaining lines of parameters. For example, this function header
def calculate_average_daily_return(customer, balance, daily_interest_rate, discount_rate): ...
could be rewritten as:
def calculate_average_daily_return(customer, balance, daily_interest_rate, discount_rate): ...
Updated by Aaron Stevens, Summer 2020