Skip to content

Set up a complete Python project with uv, Ruff, Pyrefly, pytest, and prek

Five tools turn an empty directory into a project that catches bugs before they reach version control. uv manages the project and its dependenciesAn external package your project needs, listed in pyproject.toml so tools can install it automatically. . Ruff lints and formats the code. Pyrefly checks types. pytest runs tests. prek wires Ruff, Pyrefly, and pytest into a Git hook that fires on every commit.

This tutorial builds a small task tracker and layers each tool in one at a time: scaffoldGenerate the initial file and folder structure for a new project. the project, write code, add linting, add type checking, add tests, then lock it all down with prek. By the end, a single git commit runs three quality gates automatically.

Everything here runs on your machine. To carry the same uv, Ruff, Pyrefly, and pytest stack into GitHub Actions and publish to PyPIThe Python Package Index, the public repository where Python packages are published and downloaded from. "pip install requests" fetches requests from PyPI. Learn more → , see Build and Publish a Python Package.

Check your starting point

Install uv and Git. You do not need Python installed; uv downloads and manages the interpreterThe program that reads and executes Python code. When you run "python3 hello.py", python3 is the interpreter. for you.

Scaffold the project

Create a new project called tasktrack:

$ uv init --no-package tasktrack
Initialized project `tasktrack` at `/path/to/tasktrack`
$ cd tasktrack

If you see Project is already initialized, a pyproject.toml already exists in that directory from a previous run. Pick a different name or remove the existing pyproject.toml.

Because we used the --no-package flag, uv created a flat project structure: pyproject.tomlThe standard configuration file for Python projects. Declares the project name, version, dependencies, build system, and tool settings in one place. Learn more → for configuration, main.py as the entry point, .python-version pinning the interpreter, and .gitignore. By default, uv init creates a packaged structure with a src/ directory instead. If Git is installed, uv also initialized a Git repository.

Notice the .python-version file. It records the Python version requested for this project. A minor-version pin such as 3.13 selects that Python release series, not one exact patch version.

Open pyproject.toml:

[project]
name = "tasktrack"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.13"
dependencies = []

The requires-python value depends on which Python versions uv finds on your system. Any version >=3.10 works for this tutorial.

Write the application code

Replace the contents of main.py with a task tracker that stores tasks with priorities:

main.py
from dataclasses import dataclass, field
from enum import Enum


class Priority(Enum):
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"


@dataclass
class Task:
    title: str
    priority: Priority = Priority.MEDIUM
    done: bool = False

    def complete(self) -> None:
        self.done = True


@dataclass
class TaskList:
    tasks: list[Task] = field(default_factory=list)

    def add(self, title: str, priority: Priority = Priority.MEDIUM) -> Task:
        task = Task(title=title, priority=priority)
        self.tasks.append(task)
        return task

    def pending(self) -> list[Task]:
        return [t for t in self.tasks if not t.done]

    def by_priority(self, priority: Priority) -> list[Task]:
        return [t for t in self.tasks if t.priority == priority]

    def summary(self) -> str:
        total = len(self.tasks)
        done = sum(1 for t in self.tasks if t.done)
        return f"{done}/{total} tasks completed"


def main() -> None:
    tracker = TaskList()
    tracker.add("Write README", Priority.HIGH)
    tracker.add("Add tests", Priority.HIGH)
    tracker.add("Update changelog", Priority.LOW)

    tracker.tasks[0].complete()

    print(tracker.summary())
    print(f"Pending: {len(tracker.pending())}")
    for task in tracker.pending():
        print(f"  [{task.priority.value}] {task.title}")


if __name__ == "__main__":
    main()

Run the remaining project commands from tasktrack/, which contains pyproject.toml, so uv uses the project’s dependencies and configuration.

Run it:

$ uv run main.py
1/3 tasks completed
Pending: 2
  [high] Add tests
  [low] Update changelog

uv run updates the lockfileA file that records the exact version of every installed package, so everyone working on the project gets identical installs. if dependencies have changed, ensures the virtual environmentAn isolated folder where Python installs packages for one project, keeping them separate from other projects and your system Python. Learn more → matches it, and runs the command within that environment. The first invocation creates the .venv/ directory and downloads the Python interpreter if needed.

Notice the new .venv/ directory. That is where the project’s Python interpreter lives. All packages you install with uv add go there.

Add Ruff for linting and formatting

Install Ruff as a development dependencyA package needed during development (testing, linting, formatting) that is not shipped to users of your project. Installed with the --dev flag. :

$ uv add --dev ruff
Resolved 2 packages in 92ms
Installed 1 package in 3ms
 + ruff==0.15.14

The --dev flag places Ruff in a separate dependency group so it stays out of production installs.

Run the linter:

$ uv run ruff check .
All checks passed!

Run the formatter:

$ uv run ruff format --check .
1 file already formatted

Both pass on the fresh code. To see Ruff catch real problems, add a few rules to pyproject.toml that go beyond the defaults:

pyproject.toml
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM"]

These rule sets cover pycodestyle errors (E), Pyflakes (F), import sorting (I), Python upgrade suggestions (UP), bugbear (B), and code simplification (SIM). Run the linter again:

$ uv run ruff check .
All checks passed!

The code is already clean, but these rules will catch issues as the project grows. Try adding an unused import to main.py to see Ruff in action:

import os
$ uv run ruff check .
main.py:1:8: F401 [*] `os` imported but unused
Found 1 error.
[*] 1 fixable with the `--fix` option.

Ruff found the unused import and offers to fix it automatically. Run uv run ruff check --fix . to remove it, or delete the line yourself. For a deeper look at Ruff’s capabilities, see the Ruff formatting and linting tutorial.

Add Pyrefly for type checking

Install Pyrefly:

$ uv add --dev pyrefly
Resolved 3 packages in 88ms
Installed 1 package in 4ms
 + pyrefly==1.1.1

Initialize Pyrefly’s configuration:

$ uv run pyrefly init
 INFO Config written to `/path/to/tasktrack/pyproject.toml`
 INFO Running pyrefly check...
 INFO 0 errors

pyrefly init writes a [tool.pyrefly] table to pyproject.toml. Without a config file, Pyrefly runs a limited basic preset and prints a reminder to initialize; the table switches it to full project checking.

Run the type checker:

$ uv run pyrefly check
 INFO Checking project configured at `/path/to/tasktrack/pyproject.toml`
 INFO 0 errors

Pyrefly infers types across every Python file, including unannotated function bodies, and reports no errors on the clean code. Adding type annotations to function signatures, as this code does, gives Pyrefly more to check.

To see Pyrefly catch a real bug, change the complete method in main.py to return the wrong type:

def complete(self) -> str:
    self.done = True
$ uv run pyrefly check
 INFO Checking project configured at `/path/to/tasktrack/pyproject.toml`
ERROR Function declared to return `str` but is missing an explicit `return` [bad-return]
  --> main.py:17:27
   |
17 |     def complete(self) -> str:
   |                           ^^^
   |
 INFO 1 error

Pyrefly caught the mismatch: the method promises to return str but never returns a value. Revert the annotation back to -> None before continuing.

Add pytest for testing

Install pytest:

$ uv add --dev pytest
Resolved 9 packages in 98ms
Installed 5 packages in 9ms
 + iniconfig==2.3.0
 + packaging==26.2
 + pluggy==1.6.0
 + pygments==2.20.0
 + pytest==9.0.3

Create a test file:

test_main.py
from main import Priority, Task, TaskList


def test_add_task():
    tracker = TaskList()
    task = tracker.add("Write docs")
    assert task.title == "Write docs"
    assert task.priority == Priority.MEDIUM
    assert not task.done


def test_complete_task():
    task = Task(title="Ship it", priority=Priority.HIGH)
    task.complete()
    assert task.done


def test_pending_excludes_done():
    tracker = TaskList()
    tracker.add("Task A")
    tracker.add("Task B")
    tracker.tasks[0].complete()
    assert len(tracker.pending()) == 1
    assert tracker.pending()[0].title == "Task B"


def test_filter_by_priority():
    tracker = TaskList()
    tracker.add("Urgent", Priority.HIGH)
    tracker.add("Routine", Priority.LOW)
    tracker.add("Also urgent", Priority.HIGH)
    high = tracker.by_priority(Priority.HIGH)
    assert len(high) == 2


def test_summary():
    tracker = TaskList()
    tracker.add("A")
    tracker.add("B")
    tracker.tasks[0].complete()
    assert tracker.summary() == "1/2 tasks completed"

Run the tests:

$ uv run pytest
========================= test session starts =========================
collected 5 items

test_main.py .....                                                [100%]

========================== 5 passed in 0.01s ==========================

Five tests, all passing. For more on pytest configuration, parametrized tests, and coverage, see the pytest tutorial.

Wire everything together with prek

The project now has three quality gates: Ruff (lint + format), Pyrefly (types), and pytest (tests). Running them manually before every commit is easy to forget. prek automates this by running hooks every time you run git commit.

Create .pre-commit-config.yaml in the project root:

.pre-commit-config.yaml
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v6.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.15.14
    hooks:
      - id: ruff-check
        args: [--fix]
      - id: ruff-format

  - repo: local
    hooks:
      - id: pyrefly
        name: pyrefly
        entry: uv run pyrefly check
        language: system
        types: [python]
        pass_filenames: false

      - id: pytest
        name: pytest
        entry: uv run pytest
        language: system
        types: [python]
        pass_filenames: false

The configuration has seven checks: trailing whitespace cleanup, end-of-file fixer, YAML validation, Ruff linting with auto-fix, Ruff formatting, type checking with Pyrefly, and tests with pytest. Ruff lint fixes run before its formatter; independent checks may run concurrently. The Pyrefly and pytest hooks use local entries with pass_filenames: false so each tool discovers files on its own.

If uv init did not create a Git repository because Git was not installed at the time, install Git and run git init inside tasktrack/ before installing the hooks.

Add prek to the project’s development dependencies and install the hooks:

uv add --dev prek
uv run prek install

Expect prek in the development group and lockfile, and an installed Git hook that runs on git commit. Both local hooks use the project’s environment and locked tools.

Make your first commit

Stage all files and commit:

$ git add .
$ git commit -m "Initial project with Ruff, Pyrefly, pytest, and prek"

Expect prek to report all seven checks passing, followed by Git’s commit summary. If a hook fails, prek blocks the commit and prints what went wrong. Fix the issue, re-stage, and commit again.

Watch the hooks catch a mistake

Open main.py and introduce two problems: an unused import at the top of the file and a wrong return type on summary.

Add import json as the first line and change the summary return annotation from str to int:

def summary(self) -> int:
    total = len(self.tasks)
    done = sum(1 for t in self.tasks if t.done)
    return f"{done}/{total} tasks completed"

Stage and try to commit:

$ git add main.py
$ git commit -m "Add feature"

Expect the commit to stop with two failed checks: Ruff removes the unused import json, and Pyrefly reports that the returned str does not match the declared int return type. YAML validation is skipped because no YAML file changed.

A hook that modifies a file fails even when its fix succeeds, because the staged version no longer matches the working tree. Run git add main.py after correcting the annotation to stage both fixes.

Fix the summary annotation back to -> str, then re-stage and commit:

git add main.py
git commit -m "Add feature"

Expect the Python and whitespace checks to pass, YAML validation to be skipped, and the commit to succeed.

Inspect the finished project

The project directory now looks like this:

  • .gitignore
  • .pre-commit-config.yaml
  • .python-version
  • main.py
  • pyproject.toml
  • README.md
  • test_main.py
  • uv.lock

The final pyproject.toml contains the project metadata, dependencies, and Ruff configuration in one file:

pyproject.toml
[project]
name = "tasktrack"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.13"
dependencies = []

[dependency-groups]
dev = [
    "prek>=0.5.11",
    "pyrefly>=1.1.1",
    "pytest>=9.0.3",
    "ruff>=0.15.14",
]

[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM"]

[tool.pyrefly]
project-includes = [
    "**/*.py*",
    "**/*.ipynb",
]

Four dev dependencies, six Ruff rule sets, and a hook configuration that enforces all of them on every commit.

Run all checks manually

You can run each tool individually outside of Git commits:

uv run ruff check .          # lint
uv run ruff format --check . # check formatting without changing files
uv run pyrefly check         # type check
uv run pytest                # run tests

To run all configured hooks against every tracked file (not just staged changes):

uv run prek run --all-files

Expect all seven checks to pass. This verifies the tracked project before pushing to a remote. For hook maintenance or an existing project using the original pre-commit runner, see the prek setup guide.

Last updated on