Copilot instructions for typed Python with built-in generics, deliberate dataclass options, PEP 257 docstrings, narrow exceptions and pytest tests.
.github/instructions/github-copilot-python-best-practices.instructions.md. Downloaded files need to be placed in that repository path.---
applyTo: "**/*"
---
# Python Instructions
Applies to: Python application and library code in this repository, and its pytest tests.
Version baseline: checked against Python 3.15 documentation and PEP 8. Read `pyproject.toml` (`requires-python`) first. The syntax below needs Python 3.10+ (`X | None`); on older versions use `Optional[X]` from `typing`.
## Type hints
- Annotate every function signature, including the return type (`-> None` too).
- Use built-in generics (`list[str]`, `dict[str, int]`) and `X | None`. Do not import `List`, `Dict` or `Optional` in new code that targets 3.10+.
- Leave obvious local variables unannotated; annotate when the inferred type would be wrong or too broad (for example, an empty list).
- Accept abstract types (`Iterable`, `Mapping`, `Sequence` from `collections.abc`) and return concrete ones.
## Data structures
Use `@dataclass` for plain records. Choose options on purpose:
- `frozen=True` for value objects that should not change after creation.
- `field(default_factory=list)` for mutable defaults; never `= []`.
- `slots=True` (3.10+) when you create many instances and do not need dynamic attributes.
Use Pydantic or another validation library at trust boundaries (HTTP, files, environment variables), not dataclasses.
```python
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class User:
id: str
email: str
name: str | None = None
roles: tuple[str, ...] = field(default_factory=tuple)
def active_admins(users: list[User], limit: int = 10) -> list[User]:
"""Return up to ``limit`` users that have the ``admin`` role.
Args:
users: Candidate users, in priority order.
limit: Maximum number of users to return. Must be >= 0.
Raises:
ValueError: If ``limit`` is negative.
"""
if limit < 0:
raise ValueError("limit must be >= 0")
return [u for u in users if "admin" in u.roles][:limit]
```
## Docstrings
- Public modules, classes and functions get a docstring (PEP 257). Follow the style the repository already uses (Google, NumPy or reST); do not mix styles.
- Document `Raises:` only for exceptions the function actually raises.
## Errors
- Catch the narrowest exception you can handle; never use a bare `except:`.
- Define an exception hierarchy per package (`class BillingError(Exception)`) for errors that callers handle.
- Re-raise with context: `raise ConfigError("missing DB_URL") from exc`.
- Log with `logger.exception(...)` inside `except` when the error is handled at that point; otherwise let it propagate.
## Tests (pytest)
- Write plain `assert` statements; use `pytest.raises` for exceptions and `@pytest.mark.parametrize` for input tables.
- Put shared fixtures in `conftest.py`; prefer factory fixtures over large shared objects.
- Test behavior through public functions; avoid asserting on private helpers.
```python
import pytest
from app.users import User, active_admins
@pytest.mark.parametrize("limit, expected", [(0, 0), (1, 1), (5, 2)])
def test_active_admins_respects_limit(limit: int, expected: int) -> None:
users = [User("1", "a@x.io", roles=("admin",)), User("2", "b@x.io", roles=("admin",)), User("3", "c@x.io")]
assert len(active_admins(users, limit)) == expected
def test_negative_limit_is_rejected() -> None:
with pytest.raises(ValueError):
active_admins([], -1)
```
## Verify before finishing
Run the project's configured tools when they are available:
- `pytest`
- the type checker (`mypy` or `pyright`)
- the formatter and linter (`ruff format` and `ruff check`, or `black` and `flake8`)
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.
Copilot
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Python 3.12 service repository uses these Copilot instructions while a developer asks for a small domain function, its record type and tests.
In app/users.py add a User record (id, email, optional name, roles) and a function that returns up to N admin users. Reject a negative limit. Add pytest tests.
Illustrative; not a recorded model run. A frozen, slotted dataclass using str | None and tuple[str, ...] with default_factory for the mutable-like default; a fully annotated function with a docstring whose Raises section lists only ValueError; parametrized pytest cases for limits 0, 1 and above the number of admins, and a pytest.raises test for -1. No typing.List/Optional imports for a 3.10+ project.
GitHub Copilot reads repository-wide custom instructions from .github/copilot-instructions.md and path-specific instructions from .github/instructions/*.instructions.md files with an applyTo glob. Copilot can also use AGENTS.md files, where the nearest file in the directory tree takes precedence. Which file types are honored depends on the surface: VS Code, Visual Studio, JetBrains, Xcode, Eclipse and GitHub.com differ.
.github/instructions/github-copilot-python-best-practices.instructions.mdStarting point, not a tested configuration for your repository. Used for files matching applyTo on surfaces that support path-specific instructions. Review the instructions, adapt the file paths and run your project's existing checks.
---
applyTo: "**/*"
---
# Python Instructions
Applies to: Python application and library code in this repository, and its pytest tests.
Version baseline: checked against Python 3.15 documentation and PEP 8. Read `pyproject.toml` (`requires-python`) first. The syntax below needs Python 3.10+ (`X | None`); on older versions use `Optional[X]` from `typing`.
## Type hints
- Annotate every function signature, including the return type (`-> None` too).
- Use built-in generics (`list[str]`, `dict[str, int]`) and `X | None`. Do not import `List`, `Dict` or `Optional` in new code that targets 3.10+.
- Leave obvious local variables unannotated; annotate when the inferred type would be wrong or too broad (for example, an empty list).
- Accept abstract types (`Iterable`, `Mapping`, `Sequence` from `collections.abc`) and return concrete ones.
## Data structures
Use `@dataclass` for plain records. Choose options on purpose:
- `frozen=True` for value objects that should not change after creation.
- `field(default_factory=list)` for mutable defaults; never `= []`.
- `slots=True` (3.10+) when you create many instances and do not need dynamic attributes.
Use Pydantic or another validation library at trust boundaries (HTTP, files, environment variables), not dataclasses.
```python
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class User:
id: str
email: str
name: str | None = None
roles: tuple[str, ...] = field(default_factory=tuple)
def active_admins(users: list[User], limit: int = 10) -> list[User]:
"""Return up to ``limit`` users that have the ``admin`` role.
Args:
users: Candidate users, in priority order.
limit: Maximum number of users to return. Must be >= 0.
Raises:
ValueError: If ``limit`` is negative.
"""
if limit < 0:
raise ValueError("limit must be >= 0")
return [u for u in users if "admin" in u.roles][:limit]
```
## Docstrings
- Public modules, classes and functions get a docstring (PEP 257). Follow the style the repository already uses (Google, NumPy or reST); do not mix styles.
- Document `Raises:` only for exceptions the function actually raises.
## Errors
- Catch the narrowest exception you can handle; never use a bare `except:`.
- Define an exception hierarchy per package (`class BillingError(Exception)`) for errors that callers handle.
- Re-raise with context: `raise ConfigError("missing DB_URL") from exc`.
- Log with `logger.exception(...)` inside `except` when the error is handled at that point; otherwise let it propagate.
## Tests (pytest)
- Write plain `assert` statements; use `pytest.raises` for exceptions and `@pytest.mark.parametrize` for input tables.
- Put shared fixtures in `conftest.py`; prefer factory fixtures over large shared objects.
- Test behavior through public functions; avoid asserting on private helpers.
```python
import pytest
from app.users import User, active_admins
@pytest.mark.parametrize("limit, expected", [(0, 0), (1, 1), (5, 2)])
def test_active_admins_respects_limit(limit: int, expected: int) -> None:
users = [User("1", "a@x.io", roles=("admin",)), User("2", "b@x.io", roles=("admin",)), User("3", "c@x.io")]
assert len(active_admins(users, limit)) == expected
def test_negative_limit_is_rejected() -> None:
with pytest.raises(ValueError):
active_admins([], -1)
```
## Verify before finishing
Run the project's configured tools when they are available:
- `pytest`
- the type checker (`mypy` or `pyright`)
- the formatter and linter (`ruff format` and `ruff check`, or `black` and `flake8`)
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Instruction support differs by surface: VS Code supports repository-wide, path-specific and AGENTS.md instructions; Visual Studio supports repository-wide and path-specific; JetBrains and Xcode use .github/copilot-instructions.md. GitHub's documentation describes AGENTS.md files stored anywhere in the repository, with the nearest file in the directory tree taking precedence, or alternatively a single CLAUDE.md or GEMINI.md in the root. Support differs by surface; GitHub's IDE page lists AGENTS.md among the instruction types for VS Code.
Documentation checked 2026-11-05: GitHub Docs: Adding repository custom instructionsGitHub Docs: Repository instructions in your IDE
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.