# Codex Python: A Practical Guide for Python Developers

URL: https://agentvera.dev/en/blog/codex-for-python/ · Published: 2026-11-01

Learn how to use the Codex coding agent on Python projects: setup, AGENTS.md, virtualenvs, type hints, ruff, pytest, working loops, and pitfalls.

**In short:**

- Codex works well in a Python repo when you give it a strict AGENTS.md with commands for venv activation, pytest, ruff, and mypy.
- Run small, verifiable steps and treat Codex as a junior engineer: review diffs and tests before merging.
- For parallel work, AgentVera can run multiple agents in git worktrees with automatic code review and checkpoints.

Codex Python is the practice of using OpenAI’s Codex CLI agent—launched with `codex` inside your project folder—to write, refactor, test, and debug Python. It works best when you treat it like a capable junior engineer: give it explicit Python tooling commands in AGENTS.md, keep a virtual environment, and require small, test-backed changes. This guide covers the setup, a working loop, pitfalls, and verification.

## Codex in a Python workflow

Python projects usually have a small set of repeatable commands: create a venv, install with pip or uv, run pytest, run ruff, run mypy. Codex is a terminal-based agent, so it can run these commands, read tracebacks and lint output, then edit the right files. That tight feedback loop is exactly what a Python developer needs. Unlike a chat assistant, Codex acts on your repository and can execute the test suite instead of guessing. The key is to put those commands and conventions in AGENTS.md so Codex does not have to infer them from a generic Python template. For a full overview of the agent, see Codex.

## Preparing a Python repo for Codex

Create AGENTS.md in the repo root. Keep it short and concrete: Python version, venv location and activation, install command, test/lint/type commands, folder layout, and rules that protect your codebase. A short example:

```markdown
# AGENTS.md
# Python project instructions for Codex

## Environment
- Use Python 3.12.
- Create and activate `.venv`:
  - Linux/macOS: `python -m venv .venv && source .venv/bin/activate`
  - Windows: `python -m venv .venv && .venv\Scripts\activate`
- Install dependencies: `pip install -e ".[dev]"`

## Commands
- Run tests: `pytest -q`
- Lint: `ruff check .`
- Format check: `ruff format --check .`
- Type check: `mypy src`

## Rules
- Source code lives in `src/mypackage/`, tests in `tests/`.
- Add type hints to all public functions and methods.
- Do not edit `pyproject.toml` without explicit approval.
- After every change, run tests, ruff, and mypy.
- In tests, use `pytest.raises(ExpectedError)` for error paths; never use bare `except:`.
```

Keep AGENTS.md under control; if it grows to several pages, Codex will still read it, but the most important commands should be at the top. pyproject.toml should already contain `[tool.pytest.ini_options]`, `[tool.ruff]`, and `[tool.mypy]` settings so the commands above are stable. If your project uses uv instead of pip, write `uv sync` and `uv run pytest` instead, but do not mix both unless you document the preference.

## Daily loop: small steps, tests, diff

Use a predictable loop: plan the change, ask Codex for a small diff, let it run the relevant tests, then review `git diff` before accepting. If the task is larger than a few files, split it into steps: add the function, add tests, refactor call sites, run mypy. Do not ask for a broad "improve the codebase" prompt. Codex responds much better to a single concrete change with a clear acceptance criterion. For more on running the CLI in a real project, see How to use Codex CLI: a step-by-step guide.

Example prompts that fit this loop:

- "Add a `--dry-run` flag to the CLI in `src/mypackage/cli.py` using argparse. Keep the flag optional and default to False. Update `tests/test_cli.py` to cover both cases."
- "Refactor `parse_config` in `src/mypackage/config.py` to return a `Config` dataclass instead of a dict. Update all call sites and add type hints."
- "Write a pytest fixture that creates a temporary SQLite database and yields a session. Use it in `tests/test_repository.py` to replace the current `setUp` logic."
- "Find all public functions in `src/mypackage` that are missing return type annotations and add them. Run mypy to verify no new errors."
- "Optimize the loop in `src/mypackage/processing.py` that builds a list of results; consider using a generator. Keep behavior identical and add a regression test."

After each prompt, run `git diff --stat` and `git diff` to see exactly what changed. If the agent says it ran tests, ask for the command and output unless you saw it in the terminal. Then run the suite yourself before committing.

## Python strengths and traps

Codex is strong at mechanical Python work: adding type hints, converting dicts to dataclasses, writing pytest tests from a function signature, fixing ruff violations, and filling in docstrings. It reads your existing style and tends to preserve imports and naming conventions if they are consistent.

The main pitfalls are Python-specific. Codex may add broad exception handling, mutate a list while iterating, ignore `None` from an optional return, or use `Any` to silence mypy. It can also create circular imports when moving code between modules, or add a dependency to `pyproject.toml` without asking. The table below shows typical tasks, a good prompt, and what to watch.

| Python task | Good prompt | What to watch |
|-------------|-------------|---------------|
| Add type hints | "Add type hints to all public functions in `src/mypackage` without changing behavior." | mypy may surface existing issues; do not accept `# type: ignore` everywhere. |
| Refactor to dataclass | "Replace the `Config` dict in `config.py` with a dataclass. Update all usages and tests." | Mutable default arguments and `__post_init__` validation logic. |
| Write pytest tests | "Create tests for `parse_query` covering empty string, invalid input, and valid input." | Overly broad `except Exception`; require `pytest.raises(ValueError, match=...)`. |
| Fix lint errors | "Run ruff and fix all reported issues in `src`." | Unrelated import reordering or line-length changes that bloat the diff. |

Watch especially for changes to `pyproject.toml`, `setup.cfg`, or lockfiles. Require a separate explicit prompt before Codex touches dependency configuration.

## Verification: pytest, ruff, mypy

Make verification part of every prompt. The safest pattern is to ask Codex to write or update tests before or alongside the implementation, not after. For example: "Add a test that reproduces the bug in `parse_date`, then fix it." That forces the agent to prove the change with pytest.

After the agent reports success, run these yourself:

- `pytest -q` for the full suite.
- `ruff check .` and `ruff format --check .` for style and import issues.
- `mypy src` for type errors.
- `git diff` to inspect the actual changes.

If a test fails, give Codex the exact failure output and the file path; do not just say "fix the tests." The agent can usually fix a single failing test quickly, but it may also try to change unrelated tests to make them pass. Always review the diff after a fix. For a second opinion on agent-written code, consider the practice described in AI code review: check what your agents write.

## Parallel agents on one Python repo

AgentVera is a desktop app that runs coding agents' real command line tools side by side in one window, each in its own terminal panel. For a Python project, the most useful facts are that many agents can work in parallel, each in its own git worktree, so one agent cannot overwrite another agent’s edits to shared `src/` or `tests/` files. When an agent’s turn ends, a second model reviews its code and findings link to file:line, which is useful for catching missing type hints or weak pytest coverage. Checkpoints snapshot every turn, so you can undo a bad refactor or dependency change in one click. Token budgets cap each agent per turn and per day, which keeps a long debugging session from exhausting your account.

## Wrap-up

Codex is not a replacement for Python judgment; it is a fast executor of well-specified changes. Put your virtualenv, pytest, ruff, and mypy commands in AGENTS.md, ask for small diffs, run the suite after every change, and review the diff. That loop turns Codex from a demo into a reliable part of a Python team’s workflow.

## Frequently asked questions

**How do I start Codex in a Python project?** Open a terminal in the project folder and run codex. Codex will read AGENTS.md from the project root, so create that file first with Python-specific commands and rules.

**Can Codex create and activate a virtual environment?** Yes, you can instruct it in AGENTS.md to use python -m venv .venv, activate it, and install dependencies. Codex will run commands in its terminal, but you should verify the environment before it runs tests.

**Does Codex understand type hints and enforce them?** Codex can write and update type hints, but enforce them with mypy as a separate check. Add mypy src to AGENTS.md so Codex runs it after changes.

**How do I keep Codex from breaking working Python code?** Require small diffs, run pytest and ruff after every change, and review git diff before accepting. Use a separate worktree or branch if you want to isolate experiments.

---

**About AgentVera.** AgentVera is a desktop app for macOS, Windows and Linux, built by Solviera Teknoloji. It runs 18 AI coding agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor, Antigravity, opencode, Hermes, Qwen Code, Kimi Code, Kiro, Amp, Droid, Goose, Vibe, Crush, Aider, Cline) side by side, per project, in real terminals with the user's own CLI installs and logins. The free plan has unlimited agents. Download: https://agentvera.dev/en/download/ · Pricing: https://agentvera.dev/en/pricing/
