1. Tooling: uv & project setup
uv
is a modern, fast replacement for pip, venv,
conda
and similar tools.
One tool for everything.
# Create new project
uv init my-project
cd my-project
# Install packages
uv add numpy matplotlib
# Run script
uv run script.py
The pyproject.toml
Every project has a pyproject.toml.
It sets the Python version and all dependencies.
uv
manages Python itself too:
if the required version is missing, it is downloaded automatically.
[project]
name = "traffic-jam"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"matplotlib>=3.10",
]
2. .py files instead of notebooks
Jupyter is only a layer on top of Python. We work directly with what Jupyter does in the background.
- Code in separate cells
- Cells can run in any order
- Hidden state: variables live on in the background
- Hard to reproduce: the result depends on the order
- Code in one file, from top to bottom
- Every run starts from scratch, no hidden state
-
Reproducible:
uv run script.pyalways gives the same result - Clean git diffs, better tooling for AI assistants
3. Variables & types
Python works out the type from the value you assign. No type declaration needed.
| Type | Example | Description |
|---|---|---|
int
|
x = 42 |
Whole number |
float
|
pi = 3.14 |
Decimal number |
str
|
name = "Hello" |
Text |
bool
|
active = True |
True or False |
list
|
numbers = [1, 2, 3]
|
List (ordered, can be changed) |
road_length = 230.0
n_vehicles = 22
spacing = road_length / n_vehicles
# f-strings for text formatting
print(f"{n_vehicles} vehicles on {road_length} m")
4. Control flow
Indentation is logic:
Python uses indentation instead of
{}
to mark blocks of code. Wrong indentation leads to errors.
Branches
speed = 25.0
if speed > 30.0:
print("Too fast!")
elif speed < 5.0:
print("Almost stopped")
else:
print("Normal flow")
Loops
# for loop
for i in range(5):
print(f"Step {i}")
# while loop
t = 0.0
while t < 10.0:
t += 0.1
List comprehensions
# Instead of:
squares = []
for x in range(10):
squares.append(x ** 2)
# Better:
squares = [x ** 2 for x in range(10)]
# With condition:
even = [x for x in range(20) if x % 2 == 0]
5. Functions
def optimal_velocity(headway: float, v_max=9.25, d_min=4.0, d_max=25.0) -> float:
"""Calculate desired velocity based on headway distance."""
if headway <= d_min:
return 0.0
elif headway >= d_max:
return v_max
return v_max * (headway - d_min) / (d_max - d_min)
headway: float
documents the expected type when there is no default value. With a default like
v_max=9.25
the type is obvious.
""", say what the function does. Required in our projects.
6. Classes
Class = blueprint | Object = one concrete instance | Method = a function that belongs to a class
class Dog:
"""A dog with a name and energy level."""
def __init__(self, name: str, energy=100):
self.name = name
self.energy = energy
def bark(self):
"""Bark and lose some energy."""
self.energy -= 10
print(f"{self.name}: Woof!")
rex = Dog("Rex")
rex.bark() # Rex: Woof!
print(rex.energy) # 90
luna = Dog("Luna", energy=50)
luna.bark() # Luna: Woof!
print(luna.energy) # 40
@dataclass
@dataclass
writes __init__,
__repr__
and
__eq__
for you.
Less boilerplate, the same functionality.
from dataclasses import dataclass
@dataclass
class Vehicle:
position: float
velocity: float
7. Modules & imports
# Standard library
import math
from pathlib import Path
from dataclasses import dataclass
# External packages (uv add ...)
import numpy as np
import matplotlib.pyplot as plt
my-project/
├── main.py # entry point
├── model.py # model classes
└── pyproject.toml # project file (uv)
# in main.py:
from model import Vehicle, TrafficModel
Always use
uv add
instead of pip install,
so that dependencies end up in pyproject.toml.
8. Good style
Everything in English
Variables, functions, classes, comments, docstrings: all in English. Code is read and shared internationally, and processed by tools that work in English.
Good variable names
a = 230.0
b = 22
x = a / b
l = []
for i in range(b):
l.append(i * x)
road_length = 230.0
n_vehicles = 22
spacing = road_length / n_vehicles
positions = []
for i in range(n_vehicles):
positions.append(i * spacing)
Summary
- Type hints where the type is not obvious
- f-strings instead of
.format() @dataclassfor data classes- List comprehensions
- Docstrings for functions, methods and classes
- Global variables
from module import *- Magic numbers without a name
-
Redundant type hints on plain variables:
x: int = 5(in a dataclass, the type is required) - Variable names in German or any language other than English