Skip to main content

uv Python Tutorial: Manage Projects Without the Mess

Updated 9 min readMarkdown

Quick answer

uv is a fast Python package and project manager from Astral: one tool that creates projects, installs dependencies, manages Python versions, and runs scripts inside their own virtual environment. This post builds a small uv project for a shop in Karachi, adds Pydantic, runs an orders report, and fixes a real missing dependency error along the way.

A small shop in Karachi takes orders over the phone and keeps them in a notebook, and the owner wants a simple script that totals sales per city. The script needs one library, Pydantic, to check each order before it is counted. That sounds like a five minute job, yet setup eats the afternoon: create a virtual environment, remember to activate it, install the library into the right place, and hope the next person repeats them. uv folds all of that into a few short commands, shown here with real output.

What I would check before using it

My first check is whether the project is really a project. A single throwaway script with no dependencies gains nothing from uv: python3 script.py already runs. The moment it imports a third-party library, or a second person needs to run it, the setup deserves a tool. The Python List Comprehensions Explained post shows the kind of plain script that needs nothing extra.

My second check is the Python version on the machine. uv can download and pin a version for the project, and the demo pins 3.12 in a .python-version file. If the team already standardises on one Python through Docker or a system package, that part matters less.

My third check is how the team installs packages today. If everyone already uses pip with a requirements file and a virtual environment, uv changes the commands but not the outcome, so the switch needs a reason. The reason here is speed and the lockfile: uv resolves dependencies fast and writes uv.lock, so every install reproduces the same versions.

My fourth check is whether the project will grow past one script. A project that stays a single file forever does not need scaffolding, but most shop scripts grow a second file within a month.

My verdict, as judgement: adopt uv for any Python project with dependencies, or any script a second person must run. Keep plain python3 for a one-off script with no imports. The recommendation flips the moment the team standardises on a different installer in CI.

Four orders, one project, and a missing dependency

Four orders belong to one small shop: Ayesha in Karachi, Rs 12,400; Bilal in Lahore, Rs 7,800; Hina in Karachi, Rs 9,600; Usman in Islamabad, Rs 15,200. The script validates each order with Pydantic and totals sales per city.

First, check the version and create the project. uv init scaffolds the folder, a pyproject.toml, and a .python-version file pinning Python 3.12.

$ uv --version
uv 0.13.9 (x86_64-unknown-linux-gnu)

$ uv init shop-orders Initialized project shop-orders at /home/hatch/workspace/.toolchains/verify/batch54-uv/shop-orders

The generated pyproject.toml starts with no dependencies, which is exactly what causes the trouble below.

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

Here is the script. Each order is a Pydantic model, so a bad total is rejected before it reaches the totals, and the totals are grouped per city with a plain dictionary.

# Orders report for The Practical Developer (uv demo).
#
# A small shop in Karachi tracks four orders. The script validates
# each order with Pydantic, then totals sales per city and prints
# a grand total and the average order value.
#
# Run from this folder:
#   uv run main.py
from collections import defaultdict

from pydantic import BaseModel, PositiveInt

class Order(BaseModel): id: int customer: str city: str items: list[str] total: PositiveInt

ORDERS = [ {"id": 101, "customer": "Ayesha", "city": "Karachi", "items": ["kurta", "dupatta"], "total": 12400}, {"id": 102, "customer": "Bilal", "city": "Lahore", "items": ["sneakers"], "total": 7800}, {"id": 103, "customer": "Hina", "city": "Karachi", "items": ["handbag", "wallet"], "total": 9600}, {"id": 104, "customer": "Usman", "city": "Islamabad", "items": ["jacket", "shalwar kameez"], "total": 15200}, ]

def main() -> None: orders = [Order(**row) for row in ORDERS] by_city: dict[str, int] = defaultdict(int) for order in orders: by_city[order.city] += order.total grand_total = sum(by_city.values()) print(f"{len(orders)} orders validated") for city in sorted(by_city): print(f" {city}: Rs {by_city[city]}") print(f"Grand total: Rs {grand_total}") print(f"Average order: Rs {grand_total // len(orders)}")

if name == "main": main()

Running it now fails, and the failure is the lesson: uv run builds the virtual environment, but Pydantic is not in the dependencies yet, so the import fails.

$ uv run main.py
Using CPython 3.12.3 interpreter at: /usr/bin/python3.12
Creating virtual environment at: .venv
   Building shop-orders @ file:///home/hatch/workspace/.toolchains/verify/batch54-uv/shop-orders
      Built shop-orders @ file:///home/hatch/workspace/.toolchains/verify/batch54-uv/shop-orders
Installed 1 package in 2ms
Traceback (most recent call last):
  File "/home/hatch/workspace/.toolchains/verify/batch54-uv/shop-orders/main.py", line 11, in <module>
    from pydantic import BaseModel, PositiveInt
ModuleNotFoundError: No module named 'pydantic'

The fix is one command: uv add installs Pydantic, records it in pyproject.toml, and writes uv.lock.

$ uv add pydantic
Resolved 6 packages in 3.17s
   Building shop-orders @ file:///home/hatch/workspace/.toolchains/verify/batch54-uv/shop-orders
      Built shop-orders @ file:///home/hatch/workspace/.toolchains/verify/batch54-uv/shop-orders
Downloading pydantic-core (2.2MiB)
 Downloaded pydantic-core
Prepared 6 packages in 2.63s
Uninstalled 1 package in 0.68ms
Installed 6 packages in 12ms
 + annotated-types==0.8.0
 + pydantic==2.14.4
 + pydantic-core==2.50.5
 ~ shop-orders==0.1.0 (from file:///home/hatch/workspace/.toolchains/verify/batch54-uv/shop-orders)
 + typing-extensions==4.16.0
 + typing-inspection==0.4.5

The same command now works, and the numbers check out: Karachi Rs 12,400 plus Rs 9,600 is Rs 22,000, and the four orders add to Rs 45,000.

$ uv run main.py
4 orders validated
  Islamabad: Rs 15200
  Karachi: Rs 22000
  Lahore: Rs 7800
Grand total: Rs 45000
Average order: Rs 11250

The thing that went wrong was running before adding the dependency, and uv made the fix obvious: the traceback names the missing module, and uv add is the command that adds it. With pip, the same error often means guessing where the library went. The Pydantic: Catch Bad Data Before It Reaches Your Database post covers the validation side in more depth, and the FastAPI Explained: Python APIs at Full Speed post shows the same library validating API requests.

Common mistakes and how to fix them

First, running uv run before adding a dependency. The symptom is ModuleNotFoundError naming the missing library, exactly as the demo showed. The fix is uv add with the library name, then run again.

Second, installing uv with plain pip on a system Python and hitting the externally managed error. The symptom is pip refusing with a note about PEP 668. The fix is the official installer from the uv docs, or pip install with the --user flag, as this demo did.

Third, letting a bad order through by checking plain dicts instead of a model. The symptom is a wrong total in the report, found only when a customer complains. The fix is the PositiveInt field in the demo: a test order with a total of -500 was rejected with "Input should be greater than 0 [type=greater_than, input_value=-500, input_type=int]", so bad data fails before it enters the totals.

Fourth, running uv commands from the wrong folder. The symptom is uv creating a fresh project, or complaining that no project was found, while the real one sits a folder up. The fix is to cd into the folder holding pyproject.toml first.

Frequently Asked Questions

Does uv replace pip and virtualenv? It replaces both for day to day work: uv creates the environment, installs packages, and runs commands in it.

Do I need to activate the virtual environment with uv? No. uv run creates and uses the .venv in the project folder on its own, so there is nothing to activate or forget.

How is uv different from Poetry or Pipenv? All three manage projects and lockfiles, but uv is a single fast binary written in Rust, and its commands cover Python installs, scripts, and tools too.

Can uv install a Python version for me? Yes. uv python install downloads a version, and uv init writes it into .python-version. The demo used the system Python 3.12.3.

Can I run a single script without a project? Yes, with uv run script.py, and a script can even declare its own dependencies in a comment block.

What to remember

  • uv init creates the project, pyproject.toml, and the Python version pin in one step.
  • uv add installs a dependency, updates pyproject.toml, and writes uv.lock.
  • uv run uses the project virtual environment with nothing to activate.
  • A missing dependency fails with ModuleNotFoundError, and uv add is the fix.
  • Validate data with a model, so a bad total fails before it reaches the report.

Where this leaves you

uv earns its place the day a Python script gains its first dependency and someone else needs to run it. The demo proved the three things that matter: the project started with one command, the missing Pydantic import failed loudly instead of using the wrong environment, and one uv add fixed it so the report printed real totals, Karachi Rs 22,000 and a grand total of Rs 45,000. Start your next Python script with uv init, add each library as you import it, and let the lockfile remember the rest. A setup that reproduces itself stops wasting afternoons.

Further reading

Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

No comments yet. Be the first to comment.