Final Project Guide: Code Style

by Elliott Hauser

17 Nov 2022

Use the below style guide to keep the code for your final project readable and standardized.

Your code style does not need to be perfect, but it should be as consistent with this guide as you can make it.

Note: I will not assess style until you turn in the final version of your code, but it’s much easier to use this guide throughout, rather than at the end. In particular, naming things is much easier to do at the outset.

Capitalization

  • Use snake_case for variable and function names.
  • Use Capital case for Python Classes.

Naming

  • Use descriptive singular nouns for variables containing a single thing. Use descriptive plural nouns for variables
  • Append _ and a data type to your variable names. The data type should be how Python writes it, so a dictionary would use _dict as its suffix.
  • Examples:
    • A string that contains a name would be name_str
    • A list of names would be names_list
  • When a function returns something, prepend it with get_ followed by the thing it returns, and the thing's data type.
  • Examples
    • A function that returns a name string would be get_name_str()
    • A function that returns a list of name would be get_names_list()

Comments/Documentation

  • Use comments to explain the function and flow of your code
  • Use docstrings (multi-line strings that use """) to document what your functions do.
    • A common format would be to describe what the function takes as parameters, anything it does, and what it returns (as applicable; not all functions do all of these).
    • Examples:
      • Takes a list of names and prints those that start with E.
      • Takes a list of names and returns a list of names sorted by last name.
      • Takes a setting and returns its value from options_dict.

Overall organization

Each Python file you write should follow roughly this structure (not all programs will have all parts, but when they do they should be in roughly this order):

  • import statements
  • Global variable definitions (as opposed to function variables, which will be inside their respective functions)
  • Class definitions
  • Function definitions
  • Main loop and/or function calls

Overall cleanliness

Your lines of code should be well spaced and clean. Follow the example of the code you're writing in. Some examples:

  • Leave spaces on either side of operators. x = 0, not x=0
  • Use blank lines to separate blocks of code that aren't related.  For instance, the assignment here is separated from the conditional:
x = 0

if x > 0:
print("x is positive")
else:
print("x is negative")
Elliott Hauser is an Assistant Professor at the UT Austin iSchool. He's hacking education as one of the cofounders of Trinket.io. Find Elliott Hauser on Twitter, Github, and on the web.