owned this note
owned this note
Published
Linked with GitHub
---
tags: resources
---
# CS200 Python Style Guide
## Introduction
By this point, you're all Java styling wizards. Now it's time to learn Python! Luckily for you, lots of style points are the same between the two languages, but there are some differences that will be outlined in this document. Be sure to read this thoroughly and *in its entirety* so your code is well-styled in Python (remember, you are partially graded on style :wink:).
## Naming
Please give variables and functions useful names!
### Modules
Module names are all lower case, with consecutive words concatenated together (like packages in Java!). Try to keep your module names as short as possible while still being descriptive. For example: `mymod`
### Classes
Class naming conventions in Python is identical to Java!
:::spoiler Click here for a refresher!
Classes should be named using nouns which describe what the class models. Class names should be written in UpperCamelCase, in which words are concatenated and every word starts with an uppercase letter. For example: `Ocean` and `TreeHouse`
:::
<br>
:::info
Exceptions in Python are also classes! Keep in mind, exception names should always end with "Error." For example: `BadDataError`
:::
### Constants
Constant naming conventions in Python is identical to Java!
:::spoiler Click here for a refresher!
Constants should have names consisting of nouns describing their content. Constant names are written in `CONSTANT_CASE`: all uppercase letters with words separated by underscores. For example: `MY_PYTHON_CONSTANT`
:::
### Everything Else
**This includes functions, fields, parameters, and variables**
Everything else is written in `snake_case`, in which all letters are lowercase with words separated by underscores. For example: `my_variable` and `exciting_new_method`
## Formatting
### Indentation
In Python, indentation is a must. Your code will not compile or run properly if you don't have the correct indentation. It can be a little finicky, though: if you use spaces to indent in some places and tabs in another your compiler will not be happy. In CS200, you should use **4 spaces** to indent all blocks of code.
:::info
You can configure your VSCode to automatically insert 4 spaces when the tab key is pressed. In the bottom right of your window in VSCode, there's a portion that will say "Spaces: \<number\>" or "Tab Size: \<number\>."
Click on that and choose "Indent using spaces" followed by "4" to have the correct settings. When you're done you should see "Spaces: 4" in the bottom corner of your code window.
:::
A new block or block-like construct in Python is preceded by a colon (`:`). Like in Java, the code within each new block should be indented by four spaces relative to the previous level. When the block ends, the indent level should return to the previous level. *This indent level applies to both code and comments throughout the block.*
```python
def check_adult(age):
if age >= 18:
print("You are officially an adult!")
else:
print("Not an adult yet...")
```
### Line Wrapping
Lines of code should **never exceed 80 characters in length**, as anything longer than that becomes less and less readable. Such lines should be wrapped appropriately.
Since Python is much more finnicky about spacing than Java is, there are a couple of rules that must be followed when wrapping lines:
1. All wrapped lines must keep the same level of indentation as the original statement
2. When wrapping on operators, the operator must start the new line
For example:
```python
# This is correct
long_argument_name = even_longer_argument_name
+ yet_another_even_longer_name
# This is not correct
long_argument_name = even_longer_argument_name +
yet_another_even_longer_name
# This is also not correct
long_argument_name = even_longer_argument_name
+ yet_another_even_longer_name
```
Another neat trick about line wrapping in Python is the backslash (`\`) character. Using the backslash at the end of a line indicates to the compiler that the expression will be continued on the next line (i.e. it's a signal that you'll be wrapping). Here's a few ways it might come in handy:
```python
# This is correct now!
long_argument_name = even_longer_argument_name \
+ yet_another_even_longer_name
# And so is this!
long_argument_name = even_longer_argument_name + \
yet_another_even_longer_name
```
Note that when wrapping with the backslash, the wrapped line of code must be indented so that the first character of the wrapped line is inline with the beginning of the expression on the original line (in this case, the equality operator).
## Commenting
The general principle of commenting is the same regardless of what language you're coding in: to clarify / explain your code to an outside observer (or to your future self!). Like in Java, you will have implementation and documentation comments in your Python code, but the syntax is somewhat different so let's go over that quickly.
### Implementation Comments
All implementation comments (whether they be multi-line, single-line, or end-of-line) should begin with a `#`. Here's what your implementation comments should look like:
```python
# This is a multi-line implementation
# comment in Python!
# This is a single-line one
x = 5 # and this is an end-of-line comment
```
### Documentation Comments
Also known as a "docstring," documentation comments in Python have a slightly different (and less picky) format than Javadoc comments have in Java.
Docstrings in Python appear directly *underneath* the declaration of each function. They should have the following format:
* One sentence summary of the function (what it does / its purpose)
* Parameter descriptions (if any)
* Return value descriptions (if any)
* Exceptions thrown (if any)
* Anything else (i.e. are there restrictions on calling this function, does the function have any side effects)
For example:
```python
def sum(x: float, y: float) -> float:
"""Sums two numbers
Parameters:
x -- the first number
y -- the second number
Returns:
A number (the sum of x and y)
Throws:
BadInputError if x or y (or both) is not a number
"""
```
All functions require type annotations on inputs and output. You can omit output annotation for functions that have no return (for example functions that only need to `print`).
Write docstrings for all functions, including helper and nested functions. A good docstring gives a description of the function, including its input(s), output, and purpose. Ideally, by looking at the docstring you know what the function does and how to use it without looking at the function body itself.
## Other Important Notes
### `self` Keyword
In Python, we use the keyword `self` to access methods and fields that are defined within the class they're referenced from. You should **always** use `self` when appropriate. The `self` keyword is very similar to the `this` keyword in Java. The primary difference between `self` and `this` is that `self` must be used as the first parameter for a method inside a Python class:
```python=
class Food:
# init method or constructor
def __init__(self, fruit: str, color: str) -> None:
self.fruit = fruit
self.color = color
def show(self) -> None:
print("fruit is", self.fruit)
print("color is", self.color)
```
### Import Statements
Just like in Java, you must import predefined classes or modules (or functions) before being able to use them in your code. When importing, you are free to import either the specific class or the module itself. For example, if you wanted to use the `randint` function from the `random` module, it would be acceptable to do either of the following:
```python
from random import randint
# code in between
num = randint(1, 10)
```
or
```python
import random
# code in between
num = random.randint(1, 10)
```
### Other Style Tips
1. Use constants where appropriate.
2. Use helper functions where appropriate.
3. Make sure your helper functions and constants are not redundant.
There is no point in making this function:
```python
def string_to_lower(s: str) -> str:
return s.lower()
```
since you could always use `s.lower()` instead.
4. `return` statements should be not be written like this:
```python
return(value)
```
but rather like this:
```python
return value
```
5. `if` statements should be written with newlines:
```python
if condition1:
print('condition1')
elif condition2:
print('condition2')
else:
print('condition3')
```
---
*Please let us know if you find any mistakes, inconsistencies, or confusing language in this or any other CS200 document by filling out the [anonymous feedback form](https://forms.gle/JipS5Y32eRUdZcSZ6)!* *(you do have to sign in but we don't see it)*