Python for AI Engineers · Part A · Lesson 1 of 26
Python setup with uv: install Python, virtual environments and projects
Install Python the way working teams do in 2026: one tool, uv, that installs Python, creates a project, manages its virtual environment and locks its packages. Every step is mapped to npm and Maven, so a Java or JavaScript developer knows exactly what each file and command is for.
⏱ 30 min3 exercises that check your codeRuns in your browser
By the end you can
- Install uv and a project-specific Python 3.12 on macOS, Linux or Windows
- Create a project with
uv initand explain every file it makes:pyproject.toml,.python-version,main.py,uv.lock,.venv - Add, remove and lock packages with
uv add,uv remove,uv lockanduv sync, and say whyuv runbeats plainpython - Choose a flat or
srclayout, point VS Code or PyCharm at the project's interpreter, and translate any npm or Maven command to uv
1Install uv, then let it install Python
uv is a single program (written in Rust, by Astral) that does the jobs Python used to split across five tools: it installs Python versions (pyenv), creates virtual environments (venv), installs packages (pip), locks versions (pip-tools, Poetry) and runs command-line tools (pipx). Think of it as nvm + npm in one, or SDKMAN + Maven.
Run the installer for your system. It downloads one file into your home folder (~/.local/bin on macOS and Linux, %USERPROFILE%\.local\bin on Windows) and adds that folder to your PATH. It does not need admin rights. If you prefer a package manager: brew install uv on macOS, or winget install --id=astral-sh.uv -e on Windows.
Then open a new terminal window (so it sees the new PATH) and run the three commands in the box below: check uv works, download Python 3.12, and list the Pythons uv can see.
curl -LsSf https://astral.sh/uv/install.sh | shcurl -LsSf https://astral.sh/uv/install.sh | shpowershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" downloading uv 0.x.y ... no checksums to verify installing to /Users/you/.local/bin uv uvx everything's installed!
uv --version
uv python install 3.12
uv python list --only-installed - Prints the uv version. If you see
command not found, the terminal is still using the old PATH: open a new one.line 1 - Downloads a ready-built Python 3.12 into uv's own folder. It does **not** touch the Python that came with your OS, so nothing on your system can break.line 2
- Lists every Python uv found: the one it just installed and any already on your machine.line 3
uv 0.x.y Installed Python 3.12.x in 1.9s + cpython-3.12.x-macos-aarch64-none (python3.12) cpython-3.12.x-macos-aarch64-none /Users/you/.local/share/uv/python/cpython-3.12.x-macos-aarch64-none/bin/python3.12
Tip You rarely need uv python install by hand: when a project asks for a Python version you do not have, uv downloads it automatically the first time you run the project. Doing it once now just makes the first run faster.
Watch out Do not pip install packages into the Python that ships with macOS (Homebrew) or Linux. Recent versions refuse with error: externally-managed-environment, and forcing it can break system tools. Every project gets its own environment instead, which is what the rest of this lesson sets up.
2uv init: what each generated file is for
uv init creates a new project folder, the same idea as npm init or a Spring Initializr download. --python 3.12 records which Python this project uses. Run it, then go into the folder.
uv init hello-ai --python 3.12
cd hello-ai Initialized project `hello-ai` at `/Users/you/hello-ai`
[project]
name = "hello-ai"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [] [project]is a **standard** table (PEP 621). uv, pip, PyCharm and every build tool read the same keys, so the file is not locked to uv.line 1- The project name. Like
namein package.json orartifactIdin a pom.line 2 - The oldest Python this project accepts. uv will not run it on Python 3.11.line 6
- Your packages go here. Empty for now:
uv addfills it in for you, so you rarely edit this list by hand.line 7
{
"name": "hello-ai",
"version": "0.1.0",
"engines": { "node": ">=20" },
"dependencies": {}
} <project>
<artifactId>hello-ai</artifactId>
<version>0.1.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
</properties>
<dependencies/>
</project> The other files uv init made, and two that appear on the first run:
| File | What it is | Java / JS equivalent | Commit it? |
|---|---|---|---|
pyproject.toml |
Project name, Python version, packages | package.json, pom.xml |
Yes |
.python-version |
One line, 3.12: the Python uv uses here |
.nvmrc, .sdkmanrc |
Yes |
main.py |
A tiny starter program (next section) | index.js, Main.java |
Yes |
README.md |
Empty project readme | same | Yes |
.gitignore |
Ignores .venv and __pycache__ |
same | Yes |
.git/ |
uv runs git init for you if git is installed |
same | (it is the repo) |
uv.lock |
Exact version of every package (appears on first run) | package-lock.json |
Yes |
.venv/ |
This project's own Python and packages (first run) | node_modules/, target/ |
No |
3Your first script, in the terminal and in the browser
Open main.py. uv put a main() function in it and this guard at the bottom: if __name__ == "__main__": main(). Python sets __name__ to "__main__" only for the file you run directly, so the guard means "call main() when this file is the program, but not when another file imports it". It is Python's public static void main.
Run it in your terminal with the command below. The first run takes a second longer because uv creates the virtual environment and the lock file.
The editable version underneath runs right here in your browser. It is the same idea with two extra lines that prove which Python you are on. Change the name and press Run.
uv run main.py Using CPython 3.12.x Creating virtual environment at: .venv Hello from hello-ai!
import sys
def greet(name: str) -> str:
return f"Hello, {name}! Welcome to Python."
def main() -> None:
print(greet("Java and JS developers"))
print("Python 3.12 or newer:", sys.version_info >= (3, 12))
print("Major version:", sys.version_info.major)
# In a real file you would write: if __name__ == "__main__": main()
main()
Expected output
Hello, Java and JS developers! Welcome to Python. Python 3.12 or newer: True Major version: 3
sys.version_info is a tuple like (3, 12, 1, ...). Tuples compare item by item, so >= (3, 12) is a correct version check. Comparing version strings is not: "3.9" > "3.12" is True, because "9" sorts after "1".
Tip Type hints like name: str and -> None are optional and not checked when the code runs. They are there for you and your editor, like JSDoc types in plain JavaScript.
4Virtual environments, explained for Java and JS developers
In Node, every project has its own node_modules, so two projects can use different versions of the same package. Python's answer is a virtual environment: a folder, here .venv, holding a link to a Python interpreter plus this project's installed packages.
Why is it needed? Unlike Maven, which keeps many versions in ~/.m2 and builds a classpath per project, a Python interpreter imports packages from one site-packages folder. Without a venv, every project on your laptop would share that folder and fight over versions. With one venv per project, each project gets exactly the packages in its lock file.
You never build .venv by hand. uv run, uv add and uv sync create it and keep it matching uv.lock. If it ever gets into a strange state, delete the folder and run uv sync: it is rebuilt in seconds.
hello-ai/
└── .venv/
├── pyvenv.cfg # which Python this venv was made from
├── bin/ # Scripts\ on Windows
│ ├── python # python.exe on Windows
│ └── activate # optional: puts this python first on PATH
└── lib/python3.12/site-packages/ # Lib\site-packages\ on Windows
├── httpx/ # the packages you add land here
└── ... - A small text file: the base Python, its version, and
include-system-site-packages = false(the venv cannot see global packages).line 3 - Not a full copy of Python, just a link to the interpreter uv installed. Running **this** file means "Python with this project's packages".line 5
source .venv/bin/activate(Windows:.venv\Scripts\activate) makes plainpythonmean this venv in the current terminal. With uv you can skip it:uv runpicks the venv for you.line 6- Where installed packages live, like
node_modules. One folder per project.line 7
Watch out Never commit .venv (it contains paths and binaries for your machine, like node_modules). Commit pyproject.toml and uv.lock; a teammate runs uv sync to get the same environment.
5Packages: uv add, uv remove, uv lock, uv sync
uv add is npm install <pkg>: it finds a compatible version on PyPI (Python's npm registry), installs it into .venv, writes it into pyproject.toml and records every exact version in uv.lock. --dev adds a tool you only need while developing, like npm install -D or Maven's <scope>test</scope>.
Run these two commands. Your version numbers will be newer than the ones shown, which is fine.
uv add httpx
uv add --dev pytest Resolved 8 packages in 312ms Installed 7 packages in 21ms + anyio==4.x.y + certifi==2026.x.y + h11==0.16.0 + httpcore==1.0.9 + httpx==0.28.1 + idna==3.x + typing-extensions==4.x.y Resolved 14 packages in 280ms Installed 5 packages in 15ms + pytest==8.3.5 ...
import tomllib # standard library: reads TOML files (Python 3.11+)
# This is pyproject.toml after the two uv add commands.
PYPROJECT = """
[project]
name = "hello-ai"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"httpx>=0.28.1",
]
[dependency-groups]
dev = [
"pytest>=8.3.5",
]
"""
config = tomllib.loads(PYPROJECT) # TOML text -> a plain dict
project = config["project"]
print("name:", project["name"])
print("needs Python", project["requires-python"])
print("runtime deps:", project["dependencies"])
print("dev deps:", config["dependency-groups"]["dev"])
Expected output
name: hello-ai needs Python >=3.12 runtime deps: ['httpx>=0.28.1'] dev deps: ['pytest>=8.3.5']
Run it: pyproject.toml is just data. Notice uv wrote httpx>=0.28.1, a range ("this version or newer"), while uv.lock holds the one exact version of httpx and of every package it pulls in, with a checksum for each. That split is the same as package.json versus package-lock.json.
| Command | What it does |
|---|---|
uv add httpx |
Install, add to dependencies, update the lock |
uv add 'httpx==0.28.1' |
Same, pinned to one exact version (quotes keep the shell happy) |
uv add --dev pytest |
Add to the dev group: installed locally, left out of a production install |
uv remove httpx |
Uninstall it, remove it from pyproject.toml and the lock |
uv lock |
Re-resolve and rewrite uv.lock without installing (after a hand edit) |
uv lock --upgrade-package httpx |
Move httpx to the newest version the range allows |
uv sync |
Make .venv match uv.lock exactly: install what is missing, remove what is extra |
uv sync --locked |
For CI: fail if uv.lock is out of date instead of changing it (like npm ci) |
uv tree |
Show the dependency tree (like npm ls or mvn dependency:tree) |
Tip Commit uv.lock. Then your laptop, your teammate's laptop, CI and the Docker image all run the exact same versions. LLM SDKs such as openai and langchain release often, and an unlocked upgrade is a common cause of "it worked yesterday".
6uv run: why not just type python?
Typing python main.py runs whichever Python is first on your PATH: maybe the system one, maybe a different project's venv you activated an hour ago. You get ModuleNotFoundError: No module named 'httpx' even though you just installed it.
uv run <command> removes that guesswork. Each time, it (1) finds the project by looking for pyproject.toml, (2) checks that .venv matches uv.lock and syncs it if not (so a teammate's new package just works after git pull), and (3) runs the command with that venv's Python. It works the same on every OS and needs no activation. It is like npm run, which always uses the project's own node_modules/.bin.
uv run main.py # run a file
uv run python # open the REPL with the project's packages
uv run pytest -q # run a tool installed in the venv
uv run python -m http.server 8000 # run a module (like java -cp ... MainClass)
uv run --with rich demo.py # add a package for this one run only
uvx ruff check . # run a tool without adding it (like npx) - The **REPL** is an interactive prompt, like
nodeorjshell. Typeimport httpxthenhttpx.__version__to check a package. Leave withexit()or Ctrl+D (Windows: Ctrl+Z then Enter).line 2 - pytest lives in the venv, so
uv runfinds it. You will run tests this way in every lab.line 3 -mruns a module by its import name instead of a file path. This one starts a static file server on port 8000; stop it with Ctrl+C.line 4--withmakes a package available for this run without writing it intopyproject.toml. Handy for a quick experiment.line 5uvxis short foruv tool run: it fetches a command-line tool into a cache and runs it, exactly likenpx.line 6
A single script outside any project can carry its own dependencies too: uv add --script fetch.py httpx writes a small # /// script comment block at the top of fetch.py listing them, and uv run fetch.py installs them into a throwaway environment. Useful for one-off tools you want to share as one file.
Watch out After source .venv/bin/activate in one terminal, python keeps pointing at that venv until you run deactivate or close the terminal, even after you cd into another project. Using uv run everywhere avoids this whole class of bug.
7Project layout: flat or src
A plain uv init gives a flat layout: your .py files sit next to pyproject.toml. That is perfect for scripts, small apps and every lab in this course: a few modules, run with uv run main.py, imported with import llm from the file llm.py.
uv init --package my-agent gives a src layout instead: code goes in src/my_agent/, a [build-system] table is added so the project can be built and installed like a library, and a [project.scripts] entry makes uv run my-agent a real command. Pick it for libraries, larger services, or anything you will publish or install elsewhere. It is close to Maven's src/main/java.
Why does src exist? In a flat layout Python can import your code straight from the current folder, so tests may pass on your laptop with files that would be missing from the built package. With src, tests import the installed package, so they catch that mistake.
hello-ai/
├── pyproject.toml
├── uv.lock
├── .python-version
├── main.py # uv run main.py
├── llm.py # import llm
├── config.py
└── tests/
└── test_llm.py # uv run pytest my-agent/
├── pyproject.toml # + [build-system], [project.scripts]
├── uv.lock
├── .python-version
├── src/
│ └── my_agent/ # import my_agent
│ ├── __init__.py
│ └── tools.py # from my_agent import tools
└── tests/
└── test_tools.py Names: the project (and command) can use dashes, my-agent, but the importable folder must use underscores, my_agent, because a dash is not allowed in a Python name. __init__.py marks a folder as a package; uv creates it for you.
Tip Start flat. Moving to src later is a ten-minute change, so do not let the choice slow you down on day one.
8Editor setup: VS Code or PyCharm
Your editor needs to know which Python to use, or it underlines every import httpx in red even though uv run works. The answer is always the project's venv: .venv/bin/python on macOS and Linux, .venv\Scripts\python.exe on Windows. Run uv sync first so the folder exists.
VS Code: install the Python extension from Microsoft (it brings Pylance for autocomplete). Open the project folder itself, not its parent. VS Code usually notices .venv on its own; if not, press Cmd+Shift+P (Windows and Linux: Ctrl+Shift+P), choose Python: Select Interpreter, and pick the entry that shows ./.venv. The interpreter you chose is shown in the status bar at the bottom right. To make it automatic for everyone who opens the repo, commit this settings file:
{
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
"python.testing.pytestEnabled": true,
"[python]": {
"editor.formatOnSave": true
}
} - Points VS Code at the project venv.
${workspaceFolder}is the open folder. On Windows use${workspaceFolder}\\.venv\\Scripts\\python.exe.line 2 - Shows your pytest tests in the Testing panel with run and debug buttons, like JUnit in IntelliJ.line 3
- Formats Python on save. Add the **Ruff** extension and
uv add --dev ruffto get a fast formatter and linter (Python's Prettier plus ESLint).line 5
PyCharm (or IntelliJ IDEA with the Python plugin): open the project folder, then go to Settings → Project → Python Interpreter → Add Interpreter → Add Local Interpreter. Recent versions offer uv as an environment type and pick up the existing .venv; on older versions choose Virtualenv → Select existing and browse to .venv/bin/python. PyCharm then indexes the packages and the red underlines disappear.
Watch out If imports are still red after picking the interpreter, you probably opened the parent folder, so the editor is looking for .venv in the wrong place. Open the folder that contains pyproject.toml.
9Cheat sheet: npm, Maven and uv side by side
Keep this table open for the first week. Every lab in this course starts with uv init, uv add and uv run, and ends with uv run pytest.
| Task | npm | Maven | uv |
|---|---|---|---|
| New project | npm init |
mvn archetype:generate |
uv init my-app |
| Project file | package.json |
pom.xml |
pyproject.toml |
| Lock file | package-lock.json |
(none by default) | uv.lock |
| Installed packages | node_modules/ |
~/.m2 + classpath |
.venv/ |
| Pick the runtime version | .nvmrc + nvm |
JDK + toolchains | .python-version (uv installs it) |
| Add a package | npm install httpx |
edit <dependencies> |
uv add httpx |
| Add a dev or test tool | npm install -D jest |
<scope>test</scope> |
uv add --dev pytest |
| Remove a package | npm uninstall x |
delete the block | uv remove x |
| Install from the lock | npm ci |
(no lock: versions are fixed in the pom) | uv sync --locked |
| Update the lock | npm update |
mvn versions:use-latest-releases |
uv lock --upgrade |
| Run the app | npm start / node index.js |
mvn spring-boot:run |
uv run main.py |
| Run tests | npm test |
mvn test |
uv run pytest |
| One-off tool | npx prettier |
(plugin) | uvx ruff |
| Dependency tree | npm ls |
mvn dependency:tree |
uv tree |
| Package registry | npmjs.com | Maven Central | PyPI (pypi.org) |
The workflow you will repeat for every AI project: uv init the folder, uv add an LLM SDK such as openai plus python-dotenv for the API key, write code, uv run it, and commit pyproject.toml with uv.lock. The first lab does exactly that against a free local model.
Tip Put uv sync --locked first in your CI pipeline and in your Dockerfile. If someone changed pyproject.toml without updating the lock, the build fails right away instead of quietly installing different versions.
Common mistakes
- Running
pip installinto the system Python (or withsudo). Use a project anduv add; the system Python belongs to your OS. - Typing
python main.pyinstead ofuv run main.py, and gettingModuleNotFoundErrorbecause a different Python ran. - Committing
.venvto git, or not committinguv.lock. It is the other way round: the lock goes in, the venv stays out. - Editing
uv.lockby hand. Changepyproject.toml(or useuv add/uv remove), then letuv lockrewrite it. - Leaving the editor on the wrong interpreter, so every import is underlined red while the code actually runs fine.
- Comparing versions as strings (
"3.9" > "3.12"isTrue). Compare tuples of numbers, likesys.version_info >= (3, 12).
Practice
Write the code, then press Check. Your work is saved in this browser.
1List the package names
Write dependency_names(text) that takes the text of a pyproject.toml and returns the names of the packages in [project].dependencies, without version ranges or extras, sorted A to Z. A project with no dependencies key returns []. Use tomllib.
import tomllib
def dependency_names(text):
config = tomllib.loads(text)
return config["project"]["dependencies"]
print(dependency_names('[project]\nname = "x"\ndependencies = ["openai>=1.50", "httpx>=0.28.1"]\n'))
Hint
Use `config["project"].get("dependencies", [])`. For each entry, the name ends at the first character that is not a letter, digit, dash, dot or underscore: `re.match(r"[A-Za-z0-9._-]+", dep).group()`.
2Does this Python satisfy requires-python?
Write satisfies(version, spec) where version is a tuple like (3, 12, 3) and spec is a minimum like ">=3.12". Return True when the version is at least the minimum. The starter compares strings, which is the classic bug: fix it by comparing tuples of numbers.
def satisfies(version, spec):
current = ".".join(str(n) for n in version)
minimum = spec.removeprefix(">=")
return current >= minimum
print(satisfies((3, 9, 0), ">=3.10"))
Hint
Turn `"3.12"` into `(3, 12)` with `tuple(int(p) for p in minimum.split("."))`, then compare `version[:len(minimum_tuple)] >= minimum_tuple`.
3Where is the venv Python?
Write venv_python(project, windows) that returns the path of the project's venv interpreter as a string: hello-ai/.venv/bin/python on macOS and Linux, hello-ai\.venv\Scripts\python.exe on Windows. This is the path you give your editor. Use pathlib.PurePosixPath and pathlib.PureWindowsPath so it works on any machine.
from pathlib import PurePosixPath, PureWindowsPath
def venv_python(project, windows):
return str(PurePosixPath(project) / ".venv" / "bin" / "python")
print(venv_python("hello-ai", False))
print(venv_python("hello-ai", True))
Hint
On Windows the folder is `Scripts` (capital S) and the file is `python.exe`. Build it with `PureWindowsPath(project) / ".venv" / "Scripts" / "python.exe"`.
Interview questions
Q1What is a Python virtual environment and why do you need one?
A folder (usually .venv) with a link to a Python interpreter and its own site-packages. An interpreter imports from one package folder, so without a venv per project, all projects would share packages and conflict on versions. It is the Python version of a per-project node_modules.
Q2What is uv and what does it replace?
A fast all-in-one Python project tool from Astral. It installs Python versions (pyenv), creates venvs (venv/virtualenv), installs packages (pip), locks them (pip-tools, Poetry) and runs CLI tools (pipx). Projects are described by a standard pyproject.toml plus a uv.lock.
Q3What is the difference between pyproject.toml and uv.lock?
pyproject.toml holds what you asked for: direct dependencies as ranges like httpx>=0.28.1. uv.lock holds what was resolved: the exact version and hash of every direct and transitive package, for every platform. Commit both; edit only the first.
Q4Why use `uv run` instead of `python`?
python runs whatever interpreter is first on PATH, which may lack your packages. uv run finds the project, syncs .venv with the lock file if needed, and runs the command with that venv, with no manual activation and the same behaviour on every OS.
Q5How would you make a Python build reproducible in CI and Docker?
Pin the Python version (.python-version, requires-python), commit uv.lock, and install with uv sync --locked (add --no-dev for production images) so the build fails if the lock is stale instead of resolving new versions.
Q6Flat layout or src layout?
Flat (code next to pyproject.toml) is simplest for apps and scripts. The src layout (src/<package>/) is preferred for libraries and larger services: tests import the installed package rather than the working folder, which catches packaging mistakes. uv init --package creates it.