Python notes

uv

Run Python REPL with uv with specific dependencies. No need to create separate venv

uv run --python 3.12 --with pandas python

Create new uv venv and project

uv venv --python=3.12
source .venv/bin/activate.fish
uv init
uv add pandas

For single file scripts you can define dependencies and Python version in the script itself:

# /// script
# requires-python = ">=3.12"
# dependencies = ["pandas", "pyarrow"]
# [tool.uv]
# exclude-newer = "2025-01-10T00:00:00Z"
# ///
print("Hello world")

To run the script

uv run test.py

uv and Docker

Astral provides Docker images with built-in uv. Check sample file in their GitHub repo. More docs here: Using uv in docker

vscode settings

Automatically format code with the Black formatter and sort imports using isort on save. .vscode/settings.json:

{
    "[python]": {
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.formatOnSave": true, 
        "editor.codeActionsOnSave": {
            "source.organizeImports": "explicit"
        },
    },
    "isort.args":["--profile", "black"],
    "black-formatter.args": [
        "--line-length=120"
    ],  
}

Add the extensions.json so that vscode will suggest these extensions when you open the project. .vscode/extensions.json:

{
    "recommendations": [
        "ms-python.black-formatter",
        "ms-python.isort"
    ]
}

(Note to self: check if I should switch to Astral Ruff extension. This seems to include support for Jupyter notebooks. Maybe format on save for the whole notebook?)