Modern Python Project Setup Guide for AI Assistants
Important
For coding agents: use these conventions when creating a project. In an existing repository, follow its checked-in tooling and instructions first. Record the commands that actually work in a short project instruction file; a link alone does not guarantee that an agent reads a page. A plain markdown version is available for tools that accept external context.
A project needs explicit choices about its layout, Python support, and checks. These defaults use uv and pyproject.toml; the complete project tutorial provides a guided build.
Choose the project layout and Python
Choose the supported Python floor before initialization. The examples select an interpreter and write that choice to .python-version; the generated requires-python declares the supported range. A development interpreter pin and a package’s supported range serve different purposes.
| Project | Initialization command | Generated layout |
|---|---|---|
| Installable application or CLI | uv init --python 3.14 project-name |
src/project_name/, build system, console entry point |
| Library | uv init --lib --python 3.14 project-name |
src/project_name/, build system, no console entry point |
| Flat script or internal tool | uv init --no-package --python 3.14 project-name |
main.py, no build system |
Use one initialization command, substituting the required Python version and project name, then enter the new directory:
cd project-nameExpect pyproject.toml, README.md, and .python-version in the new project. --no-package keeps the project layout flat (a main.py at the top level instead of a src/ package). On uv releases from before uv init became packaged-by-default, pass --package for the installable application layout.
Use the generated console entry point for a CLI; implement its existing function instead of adding a duplicate [project.scripts] table. A library has no generated console command. See uv project types for the layout trade-offs.
Configure the project’s checks
Add dependencies that the project needs
Add runtime packages with uv add, replacing this example with packages the application actually imports:
uv add requestsExpect the dependency in the dependencies array under [project], a generated or updated uv.lock, and an environment at .venv. Add version constraints only when the project’s compatibility requirements justify them; avoid copying an old framework constraint into a new project.
Keep metadata in the standard project table and development tools in dependency groups. For a project with no runtime dependencies, adding the development tools also creates its environment and lockfile.
Configure testing with pytest
uv add --dev pytest
mkdir testsThe --dev flag marks pytest 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.
, keeping it out of production installs. Expect it in [dependency-groups].dev and a new tests/ directory.
Add the following table to pyproject.toml:
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["--strict-markers", "--strict-config"]Add runnable tests before treating setup as complete. An empty tests/ directory produces pytest exit code 5, not a passing result; tests/__init__.py is not required for discovery. Follow testing with pytest and uv for a runnable example, or measure coverage when coverage is needed.
Configure Ruff for linting and formatting
uv add --dev ruffExpect Ruff in the development group and lockfile. Add this configuration to pyproject.toml:
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
]
ignore = ["E501"] # Accept formatter output, including lines it cannot wrapRuff discovers this pyproject.toml and infers its Python target from requires-python when target-version is omitted. Keep an explicit target only when the project needs a different policy. Formatting attempts to wrap long lines but does not guarantee that every line fits the configured limit; ignoring E501 accepts that behavior.
Configure the adopted type checker
For a new setup, use Pyrefly; in an existing project, keep its chosen checker:
uv add --dev pyreflyExpect Pyrefly in the development group and lockfile. Add this table before checking:
[tool.pyrefly]
preset = "default"Without native or migratable checker configuration, Pyrefly selects a basic preset that silences many diagnostics. An explicit preset records the intended checking behavior. If the project uses ty, mypy, or Pyright, record that checker’s command instead. See How do Python type checkers compare? before choosing a different checker.
A configured checker still needs to run during the task. For Claude Code, connect its results through a skill and bounded hook; for Codex, require recorded type-check results and retain the CI check. Start from a passing baseline or explicitly scoped errors rather than asking the agent to fix every pre-existing diagnostic.
Install and exercise Git hooks
Git must be installed and the project must be a Git repository; run git init first if initialization did not create one. Use prek as the default runner for a new project. It reads .pre-commit-config.yaml; add the runner as a project development dependency:
uv add --dev prek
uv run prek installuv run executes the command inside the project’s virtual environment, ensuring all dependencies are installed first. Expect prek in the development group and an installed Git hook.
Create .pre-commit-config.yaml:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.5
hooks:
- id: ruff-check
args: [--fix]
- id: ruff-format
- 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
- id: check-toml
- id: check-added-large-filesAfter reviewing and staging the new project’s files, exercise the hooks:
uv run prek run --all-filesExpect hook environments to download on the first run, then a result for each hook. If a hook changes files, inspect the diff, stage the intended changes, and rerun until all hooks pass. Provision these downloads during setup when the task itself has restricted network access.
Keep hook revisions maintained with uv run prek update, then review the diff and run the hooks again. The Ruff hook and the locked project Ruff use separate environments; compare the hook’s rev with uv run ruff --version and keep their versions consistent.
pre-commit remains an alternative for projects that use the original runner: add it with uv add --dev pre-commit, then use uv run pre-commit install and uv run pre-commit run --all-files. Use one runner for the project. For a migration, keep the YAML configuration and replace the installed shim with uv run prek install -f; see setting up prek hooks.
Use uv run for locked project tools and uvx for disposable, one-off tool runs. uvx does not select versions from the project lockfile. For hook installation, use a project dependency as shown here or a persistent uv tool install installation; a Git hook must still find its runner on later commits after disposable caches are cleaned.
Give each agent the project contract
Use the instruction format supported by the client that runs the task:
| Client | Project instructions |
|---|---|
| Codex | AGENTS.md |
| Claude Code | CLAUDE.md, or AGENTS.md according to its project-instructions mode |
| Cursor | AGENTS.md or project rules in .cursor/rules/*.mdc |
| GitHub Copilot | .github/copilot-instructions.md; support for AGENTS.md depends on the client and feature |
| Gemini CLI | GEMINI.md; other filenames require context.fileName configuration |
By default, Claude Code loads AGENTS.md only when no project CLAUDE.md, .claude/CLAUDE.md, or CLAUDE.local.md exists in the working directory or its ancestors. User-level ~/.claude/CLAUDE.md and managed instructions do not disable this fallback. To share instructions when those files coexist, import AGENTS.md with a standalone @AGENTS.md line in CLAUDE.md, or select the mode that reads both under Project instructions in /config. Check Claude Code’s instruction-loading documentation if support is unavailable.
Once the tools are installed, configured, and locked, adapt this instruction block to the actual project. It assumes the installable layout, runnable tests, and the Pyrefly setup described here:
Use uv for dependencies and project commands. Keep uv.lock committed.
Source: src/project_name/. Tests: tests/.
Setup: uv sync --locked
Checks:
```bash
uv run --locked ruff check .
uv run --locked ruff format --check .
uv run --locked pytest
uv run --locked pyrefly check
```
Report the commands run, their exit codes, and anything that could not run.Replace the source path for a flat project and the type-check command for a different checker; omit type checking only when the project has not adopted one. Put optional procedures in skills when supported. Instructions provide context, hooks run automation, permissions control tool access, and CI verifies the committed result.
Use the AGENTS.md how-to, Claude Code uv configuration, or Cursor project rules for client-specific setup. Check Copilot’s instruction support for the surface in use.
Prepare the environment where the task runs
A local terminal, editor, worktree, and cloud task may each use a different checkout and environment. Installing dependencies on a laptop does not prepare a remote runner.
In an existing uv project with a committed lockfile, run:
uv sync --locked
uv run --locked python -c "import sys; print(sys.executable)"Expect .venv in that checkout and an interpreter path inside it, unless the project overrides the environment location. --locked rejects dependency metadata that no longer matches the lockfile. When deliberately changing dependencies, use uv add, uv remove, or uv lock, then commit the updated metadata and lockfile together.
Provision uv, the selected Python, and private-index credentials through the runner’s setup and secrets controls. Confirm package and hook downloads work during setup when task-time network access is restricted. Keep a separate environment for each worktree; isolate parallel tasks with worktrees.
Verify the setup before shipping
Run the project contract’s checks and confirm their exit codes. Expect a lint success summary, a formatter result indicating files are unchanged, collected and passing tests, and zero type errors for the configured scope. A formatter success does not prove tests passed; pytest reporting no tests is not a successful test run.
Before completing setup, verify:
- The layout and Python support range match the project’s purpose
-
uv.lockis committed withpyproject.toml; the selected Python is recorded in.python-version -
.gitignoreexcludes.venvand generated caches - The README documents setup, usage, and the same checks as the instruction file
- Tests are collected and pass; lint, formatting, and the adopted type checker pass
- Git hooks are installed and pass against all intended tracked files
- CI runs the same checks as the project contract
Run the same checks in CI
For the setup with Pyrefly described here, save this as .github/workflows/test.yml. If the project uses another checker, replace that step; remove it when no checker is configured.
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7.0.1
- uses: astral-sh/setup-uv@v10.3.3
with:
enable-cache: true
- name: Install dependencies
run: uv sync --locked
- name: Lint
run: uv run --locked ruff check .
- name: Check formatting
run: uv run --locked ruff format --check .
- name: Test
run: uv run --locked pytest
- name: Check types
run: uv run --locked pyrefly checkExpect a separate result for each check in the job. The GitHub Actions tutorial covers matrices and caching; uv manages the project interpreter without requiring a separate actions/setup-python step.
Maintain dependencies after setup
- Automate updates. Configure Dependabot for
uv,github-actions, andpre-commit; the last updates the.pre-commit-config.yamlused by prek. Review lockfile and hook changes, then run the project’s checks before merging. - Set a dependency cooldown. Start with a seven-day window in checked-in uv configuration, then regenerate
uv.lock. A cooldown delays new releases, including security fixes; configure the cooldown and urgent-patch exceptions. Waiting does not establish that a package is safe. - Scan for known vulnerabilities. Add
uv audit --lockedto CI, using the dependency-scanning guide for the workflow and handling findings. The command requires network access, remains a preview feature, and exits non-zero when vulnerabilities are found. It checks known advisories rather than proving dependencies are safe.
Keep shared project files consistent
The README should name the actual launch command: uv run project-name for the generated console entry point, or uv run python main.py for the flat layout. A library should document its import or public API instead. Link to the project contract’s checks rather than maintaining conflicting command lists.
Extend .gitignore only for generated files that the project creates, for example:
.pytest_cache/
.coverage
htmlcov/
.ruff_cache/Commit portable editor settings such as .vscode/settings.json when they are part of the shared workflow. Avoid a blanket .vscode/ ignore rule that hides those files; keep machine-specific paths out of committed settings. Follow the VS Code or PyCharm instructions for interpreter discovery, Ruff, and pytest.
Use uv.lock as the dependency lock for a new uv project. Preserve intentional requirements.txt compatibility workflows; export from the project when an integration needs that format. See exporting requirements rather than treating requirements files or pip interoperability as inherently wrong.
Distinguish lock maintenance from dependency upgrades: uv lock refreshes the lockfile while retaining existing selections when possible; uv lock --upgrade deliberately allows upgrades. Keep linting, formatting, and test infrastructure proportional to the project: a throwaway script does not need every check in this setup.