Skip to content

Commit 9c53b5f

Browse files
Python: Refresh coding standards and Copilot review guidance (#9637)
* Python: Refresh coding standards and Copilot guidance Co-authored-by: Copilot App <[email protected]> * Python: Address coding standards review feedback Co-authored-by: Copilot App <[email protected]> * Python: Address additional standards review feedback Co-authored-by: Copilot App <[email protected]> --------- Co-authored-by: Copilot App <[email protected]>
1 parent 3b725b3 commit 9c53b5f

9 files changed

Lines changed: 454 additions & 844 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
applyTo: 'dotnet/**'
3+
---
4+
5+
Before reviewing .NET changes, read and apply
6+
[dotnet/AGENTS.md](../../dotnet/AGENTS.md). Use the task-specific skills under
7+
`dotnet/.github/skills/` for build and test commands, project structure, pull
8+
requests, and sample verification.
9+
10+
Do not duplicate purely mechanical findings that `dotnet format`, analyzers, or
11+
other required CI checks will report.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
applyTo: 'python/**'
3+
---
4+
5+
Before reviewing Python changes, read and apply the canonical
6+
[Python coding standards](../../python/CODING_STANDARD.md). Use
7+
[python/AGENTS.md](../../python/AGENTS.md) and the nearest package or sample `AGENTS.md`
8+
for task-specific architecture and workflow guidance.
9+
10+
- Review new or materially edited code against the standards. Do not report unrelated legacy convention violations
11+
elsewhere in a touched file.
12+
- Independently report material correctness or security defects visible in affected files, even when they predate
13+
the changed lines.
14+
- Treat `MUST` and `MUST NOT` violations as review findings.
15+
- Report `SHOULD` and `SHOULD NOT` violations when they have a material correctness, API, maintainability,
16+
performance, or usability impact.
17+
- Do not report `MAY` choices as violations.
18+
- Do not duplicate purely mechanical findings that Ruff, Pyright, or another required CI check will report.

‎python/.github/instructions/python.instructions.md‎

Lines changed: 0 additions & 10 deletions
This file was deleted.
Lines changed: 43 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -1,127 +1,48 @@
11
---
22
name: python-development
33
description: >
4-
Coding standards, conventions, and patterns for developing Python code in the
5-
Agent Framework repository. Use this when writing or modifying Python source
6-
files in the python/ directory.
4+
Workflow guidance for developing Python code in the Agent Framework
5+
repository. Use this when writing or modifying Python source files under
6+
python/.
77
---
88

9-
# Python Development Standards
10-
11-
## File Header
12-
13-
Every `.py` file must start with:
14-
15-
```python
16-
# Copyright (c) Microsoft. All rights reserved.
17-
```
18-
19-
## Type Annotations
20-
21-
- Always specify return types and parameter types
22-
- Use `Type | None` instead of `Optional[Type]`
23-
- Use `from __future__ import annotations` to enable postponed evaluation
24-
- Use suffix `T` for TypeVar names: `ChatResponseT = TypeVar("ChatResponseT", bound=ChatResponse)`
25-
- Use `Mapping` instead of `MutableMapping` for read-only input parameters
26-
- Prefer `# type: ignore[...]` over unnecessary casts, or `isinstance` checks, when these are internally called and executed methods
27-
But make sure the ignore is specific for both mypy and pyright so that we don't miss other mistakes
28-
- Internal private helpers may be used across `agent_framework*` modules when intentional; use a targeted
29-
`# pyright: ignore[reportPrivateUsage]` instead of making the helper public just to satisfy pyright.
30-
- Do not add trivial pass-through or one-line helper functions solely to appease typing. Prefer targeted ignores,
31-
casts, or clearer annotations over adding runtime overhead without a design benefit.
32-
33-
## Function Parameters
34-
35-
- Positional parameters: up to 3 fully expected parameters
36-
- Use keyword-only arguments (after `*`) for optional parameters
37-
- Provide string-based overrides to avoid requiring extra imports:
38-
39-
```python
40-
def create_agent(name: str, tool_mode: Literal['auto', 'required', 'none'] | ChatToolMode) -> Agent:
41-
if isinstance(tool_mode, str):
42-
tool_mode = ChatToolMode(tool_mode)
43-
```
44-
45-
- Avoid shadowing built-ins (use `next_handler` instead of `next`)
46-
- Avoid `**kwargs` unless needed for subclass extensibility; prefer named parameters
47-
48-
## Docstrings
49-
50-
Use Google-style docstrings for all public APIs:
51-
52-
```python
53-
def equal(arg1: str, arg2: str) -> bool:
54-
"""Compares two strings and returns True if they are the same.
55-
56-
Args:
57-
arg1: The first string to compare.
58-
arg2: The second string to compare.
59-
60-
Returns:
61-
True if the strings are the same, False otherwise.
62-
63-
Raises:
64-
ValueError: If one of the strings is empty.
65-
"""
66-
```
67-
68-
- Always document Agent Framework specific exceptions
69-
- Explicitly use `Keyword Args` when applicable
70-
- Only document standard Python exceptions when the condition is non-obvious
71-
72-
## Import Structure
73-
74-
```python
75-
# Core
76-
from agent_framework import Agent, Message, tool
77-
78-
# Components
79-
from agent_framework.observability import enable_sensitive_telemetry
80-
81-
# Connectors (lazy-loaded)
82-
from agent_framework.openai import OpenAIChatClient
83-
from agent_framework.foundry import FoundryChatClient
84-
```
85-
86-
## Public API and Exports
87-
88-
In `__init__.py` files that define package-level public APIs, use direct re-export imports plus an explicit
89-
`__all__`. Avoid identity aliases like `from ._agents import Agent as Agent`, and avoid
90-
`from module import *`.
91-
92-
Do not define `__all__` in internal non-`__init__.py` modules. Exception: modules intentionally exposed as a
93-
public import surface (for example, `agent_framework.observability`) should define `__all__`.
94-
95-
```python
96-
__all__ = ["Agent", "Message", "ChatResponse"]
97-
98-
from ._agents import Agent
99-
from ._types import Message, ChatResponse
100-
```
101-
102-
Special case: the root `agent_framework/__init__.py` uses lazy runtime exports. For root public API changes:
103-
- Add the symbol to `_LAZY_MODULE_EXPORTS` and keep `_LAZY_EXPORTS` derived from it.
104-
- Keep the explicit runtime `__all__` synchronized; it is still required for `from agent_framework import *`.
105-
- Add the same public symbol to `agent_framework/__init__.pyi` so pyright, mypy, and editors see the typed surface.
106-
- Put runtime deprecation behavior in the owning module via that module's `__getattr__`; avoid root-level
107-
special-case branches for individual deprecated exports.
108-
- Identity aliases are appropriate in `.pyi` stubs because they mark re-exported names for type checkers; avoid them
109-
in runtime `.py` modules unless there is a specific compatibility reason.
110-
111-
## Performance Guidelines
112-
113-
- Cache expensive computations (e.g., JSON schema generation)
114-
- Prefer `match/case` on `.type` attribute over `isinstance()` in hot paths
115-
- Avoid redundant serialization — compute once, reuse
116-
117-
## Style
118-
119-
- Line length: 120 characters
120-
- Format only files you changed, not the entire codebase
121-
- Prefer attributes over inheritance when parameters are mostly the same
122-
- Async by default — assume everything is asynchronous
123-
124-
## Naming Conventions for Connectors
125-
126-
- `_prepare_<object>_for_<purpose>` for methods that prepare data for external services
127-
- `_parse_<object>_from_<source>` for methods that process data from external services
9+
# Python Development Workflow
10+
11+
The canonical engineering rules are in
12+
[`python/CODING_STANDARD.md`](../../../CODING_STANDARD.md). Read and apply that
13+
document before changing Python source. Do not create or maintain a competing
14+
copy of the standards in this skill.
15+
16+
## Before Editing
17+
18+
1. Read `python/AGENTS.md` and the nearest package `AGENTS.md`.
19+
2. Identify whether the change affects package source, tests, samples, public
20+
exports, package governance, or more than one of those surfaces.
21+
3. Read the task-specific skill when applicable:
22+
- `python-testing` for test design, integration markers, and test commands.
23+
- `python-code-quality` for formatting, linting, and type checking.
24+
- `python-package-management` for package creation, dependencies, public
25+
lazy exports, and package lifecycle.
26+
- `python-feature-lifecycle` for staged API decorators and promotion.
27+
28+
## Implementing Changes
29+
30+
- Follow established patterns in the owning package unless they conflict with
31+
`python/CODING_STANDARD.md`.
32+
- Keep the common public path import-light and review public API changes for
33+
compatibility and ergonomics.
34+
- Update source, typing surfaces, tests, samples, and documentation together
35+
when they represent the same contract.
36+
- For root `agent_framework` export changes, follow the synchronized runtime,
37+
`__all__`, and `.pyi` workflow in `python-package-management`.
38+
- Do not broaden a change into unrelated cleanup solely because nearby code
39+
predates the current standard.
40+
41+
## Validation
42+
43+
Run the smallest relevant commands from `python/`. Use
44+
`python-code-quality` and `python-testing` to select package-scoped syntax,
45+
typing, and test commands before escalating to broader checks.
46+
47+
When a convention, command, or workflow changes, update the canonical document
48+
or owning task-specific skill rather than duplicating the new guidance here.

‎python/.github/skills/python-testing/SKILL.md‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@ description: >
1010
CI enforces at least 85% line coverage for every package classified Beta or Production/Stable.
1111
Alpha packages are report-only, and the DevUI and experimental Lab packages are excluded from
1212
aggregate coverage enforcement. Tests should be fast, reliable, and maintainable.
13-
When adding new code, check that the relevant sections of the codebase are covered by tests, and add new tests as needed. When modifying existing code, update or add tests to cover the changes.
13+
Test observable behavior first, and use coverage as a backstop. Meaningful new branches, error paths,
14+
and edge cases must be covered without coupling tests to implementation details.
15+
Before writing new tests, inspect the existing tests and coverage for the affected behavior. For refactors and
16+
behavior-preserving implementation changes, update existing tests when they already express the contract. Add new
17+
tests for new behavior, regressions, or a meaningful coverage gap rather than by default for every production edit.
1418
We run tests in two stages, for a PR each commit is tested with unit tests only (using `-m "not integration"`), and the full suite including integration tests is run when merging.
1519

1620
When an API is marked as deprecated, migrate ordinary tests to its replacement in the same change. Retain only
@@ -83,25 +87,30 @@ packages/core/
8387

8488
- Use `conftest.py` for shared fixtures within a test directory
8589
- Before adding new fixtures, check if existing ones can be reused or extended
90+
- For reusable setup that needs call-time parameters, use a fixture that returns a callable factory
91+
- Consume fixtures through pytest injection; do not import fixtures or helpers from `conftest.py`
92+
- Put non-fixture helpers in a normal helper module and import them explicitly
8693
- Use descriptive names: `mapper`, `test_request`, `mock_client`
8794

8895
## File Naming
8996

9097
- Files starting with `test_` are test files — do not use this prefix for helpers
9198
- Prefer extending an existing test file that already covers the same component or behavior; create a new file only for a distinct surface without an appropriate existing file
92-
- Use `conftest.py` for shared utilities
99+
- Use `conftest.py` for shared fixtures and normal helper modules for other shared utilities
93100

94101
## Integration Tests
95102

96-
Integration tests require external services (OpenAI, Azure, etc.) and are controlled by three markers:
103+
Integration tests require external services (OpenAI, Azure, etc.) and must be selectable and safely skippable:
97104

98-
1. **`@pytest.mark.flaky`** — marks the test as potentially flaky since it depends on external services
99-
2. **`@pytest.mark.integration`** — used for test selection, so integration tests can be included/excluded with `-m integration` / `-m "not integration"`
100-
3. **`@skip_if_..._integration_tests_disabled`** decorator — skips the test when the required API keys or service endpoints are missing
105+
1. **`@pytest.mark.integration`** — used for test selection, so integration tests can be included/excluded with `-m integration` / `-m "not integration"`
106+
2. **`@skip_if_..._integration_tests_disabled`** decorator — skips the test when the required API keys or service endpoints are missing
107+
3. **`@pytest.mark.flaky`** — add this only when the test is genuinely nondeterministic or service-sensitive
101108

102109
### Adding New Integration Tests
103110

104-
All three markers must be applied to every new integration test:
111+
Every new integration test must have the integration marker and provider-specific skip condition. Add the flaky
112+
marker when the scenario depends on timing, eventual consistency, a nondeterministic model response, or another
113+
service-sensitive condition:
105114

106115
```python
107116
@pytest.mark.flaky
@@ -160,5 +169,7 @@ The `python-tests-misc-integration` job is intended for small integration test s
160169

161170
- Run only related tests, not the entire suite
162171
- Review existing tests to understand coding style before creating new ones
172+
- Test through the public or observable contract
173+
- Mock external boundaries rather than the internal unit whose behavior the test should prove
163174
- Use print statements for debugging, then remove them when done
164175
- Resolve all errors and warnings before committing

‎python/AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ Instructions for AI coding agents working in the Python codebase.
44

55
**Key Documentation:**
66
- [DEV_SETUP.md](DEV_SETUP.md) - Development environment setup and available poe tasks
7-
- [CODING_STANDARD.md](CODING_STANDARD.md) - Coding standards, docstring format, and performance guidelines
7+
- [CODING_STANDARD.md](CODING_STANDARD.md) - Canonical Python engineering and API-design standards
88
- [samples/SAMPLE_GUIDELINES.md](samples/SAMPLE_GUIDELINES.md) - Sample structure and guidelines
99
- [Python function-calling loop specification](../docs/specs/004-python-function-calling-loop.md) - Required
1010
behavior, scenario-to-test mapping, coverage gaps, and extra validation for function-loop changes
1111

1212
**Agent Skills** (`.github/skills/`) — detailed, task-specific instructions loaded on demand:
13-
- `python-development` — coding standards, type annotations, docstrings, logging, performance
13+
- `python-development` — Python development workflow and routing to the canonical standards and task-specific skills
1414
- `python-testing` — test structure, fixtures, async mode, running tests
1515
- `python-code-quality` — linting, formatting, type checking, prek hooks, CI workflow
1616
- `python-feature-lifecycle` — package-stage meaning plus staged API decorators, enums, and feature promotion

0 commit comments

Comments
 (0)