Python Notes

Table of Contents


Naming conventions

Specified in PEP-0008:


You can use the typing module to provide type hints. This is more for documentation since there’s no checking.

from typing import Dict, List, Tuple

Vector = List[float]

def my_func(vec: Vector, thing: MyClass) -> None:


Using the dataclasses module:

from dataclasses import dataclass

class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

item = InventoryItem("Toy", 25.0, 3)


You can use the abc module.

from abc import ABC, abstractmethod

from logic.model import Recipe

class Store(ABC):
    def add_recipe(self, recipe: Recipe) -> None:

    def get_recipes(self) -> Recipe:

class InMemoryStore(Store):
    # ...


Use pytest. Install and run with (ensure you’re doing the dependency management bit below):

pip install -U pytest

Tests are methods that begin with test_ and you use the standard language assert. Pytest will recursively look for any files named test_*.py or * (more here).

Web Server

Bottle is a decent web server to use.

from bottle import Bottle, request, route, run

app = Bottle()

def hello():
    # Query parameters like http://localhost:8080?name=John
    name = or "Peter"
    return "Hello " + name'localhost', port=8080, debug=True)

Dependency Management

To keep your Python environments nice and clean, use VirtualEnv.

TODO: Update this to use venv instead of virtualenv.


pip install --user virtualenv

Project Setup

In the project directory:

virtualenv ENV

This will create an ENV directory.


Whenever you want to do anything in your project, run:

source ENV/bin/activate

Now you can install things normally with pip, eg:

pip3 install torch torchvision

Once you’re done, run deactivate.


To save the state of your environment, run:

pip freeze > requirements.txt

And then somebody else can run:

pip install -r requirements.txt

Python Tools

To start a local HTTP server:

python -m SimpleHTTPServer 8080  # Python 2
python -m http.server 8080       # Python 3


Docker packaging guide for Python