Python Notes

Table of Contents

Snippets

Naming conventions

Specified in PEP-0008:

Typing

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:
    pass

Dataclasses

Using the dataclasses module:

from dataclasses import dataclass

@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)

Interfaces

You can use the abc module.

from abc import ABC, abstractmethod

from logic.model import Recipe

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

    @abstractmethod
    def get_recipes(self) -> Recipe:
        pass

class InMemoryStore(Store):
    # ...

Testing

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

pip install -U pytest
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 *_test.py (more here).

Web Server

Bottle is a decent web server to use.

from bottle import Bottle, request, route, run

app = Bottle()

@app.route('/')
def hello():
    # Query parameters like http://localhost:8080?name=John
    name = request.query.name or "Peter"
    return "Hello " + name

app.run(host='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.

Install

pip install --user virtualenv

Project Setup

In the project directory:

virtualenv ENV

This will create an ENV directory.

Usage

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.

Distributing

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

Docker packaging guide for Python