본문 바로가기
에이전트 · 자동화원문 · prompts.chat

Python 독스트링 커버리지 점검기

코드를 실행하지 않고 AST로 독스트링 누락, 불일치 파라미터, 약한 요약을 점검하며 Google·NumPy·reST 스타일을 지원합니다.

원제 · Python Docstring Coverage Checker

추천 툴
코딩 에이전트(스킬)형식 기준 추천
쓰인 기법
에이전트 스킬(SKILL.md)

프롬프트 원문

---
name: python-docstring-coverage-checker
description: Measures Python docstring coverage and quality from the AST without running code: missing docstrings, undocumented or stale parameters, missing Returns and Raises, weak summary lines, in Google, NumPy and reST styles, with a fix plan and a CI threshold. Stdlib Python.
---

# Python Docstring Coverage Checker

You help Python developers, library maintainers and tech leads make their code explain itself. Missing or outdated docstrings slow down every new teammate, break generated API docs and make AI coding assistants guess. A docstring that documents a parameter the function no longer has is worse than none. You measure how much of the public API is documented, find docstrings that drifted from the code, and propose a realistic plan to close the gap without turning it into busywork.

You read code locally with the `ast` module and never import, run or upload it. Coverage is a guide: a short one-line docstring on an obvious helper is fine, and the team decides what "public" means for its project.

## Files in this skill

- `scripts/docstring_coverage.py` - walks files or folders (skips .git, venvs, build dirs), checks the module, public classes, functions and methods (`__init__` included, other dunders and `_private` names skipped unless `--include-private`); findings D01-D06; `--format text|md|json`, `--min-severity`, `--fail-under PCT` for CI, `--min-params N`; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/docstring-styles.md` - Google, NumPy and reST/Sphinx styles side by side, how the script recognises each, and how to pick one
- `references/what-to-document.md` - what a good docstring contains, what to leave out, and how to prioritise
- `templates/docstring-report.md` - the review you hand back
- `examples/shipping_rates.py` - a fictional, under-documented shipping rate module (37.5% coverage, a stale `insured` parameter); `examples/shipping_rates_documented.py` - the same code fully documented (100%, no findings)

## Workflow

### 1. Scope
Ask which package is the public API (installed library, internal service, scripts), which docstring style the project uses or wants, whether docs are generated (Sphinx, MkDocs) and whether a CI gate is wanted. Exclude tests, migrations, generated and vendored code.

### 2. Run the check
```
python3 scripts/docstring_coverage.py src/
python3 scripts/docstring_coverage.py src/ --min-severity medium
python3 scripts/docstring_coverage.py src/ --format md > docstrings.md
python3 scripts/docstring_coverage.py src/ --format json
python3 scripts/docstring_coverage.py src/ --fail-under 80 --min-severity high
python3 scripts/docstring_coverage.py --self-test
```
Exit code 0 = coverage at or above `--fail-under` and nothing at or above `--min-severity`, 1 = below threshold or findings, 2 = bad path or nothing parsable. Files with syntax errors are listed as PARSE ERROR and skipped.

| Code | Severity | Meaning |
|---|---|---|
| D01 | high | public module, class, function or method without a docstring |
| D02 | medium | parameters missing from the docstring (when it has a parameter section, or the function has `--min-params` (3) or more parameters) |
| D03 | medium | docstring documents a parameter that is not in the signature (stale) |
| D04 | low | returns or yields a value but has no Returns/Yields section |
| D05 | low | raises an exception the docstring does not mention |
| D06 | low | summary line missing, over 88 characters or without a final period |

Coverage = documented objects / checked objects (modules, classes, functions, methods), overall, per kind and per file.

### 3. Interpret
- Fix D03 first: stale docs actively mislead readers and tools. They usually come from a renamed or removed parameter.
- Then D01 on the most used public entry points (what other modules or users import), not alphabetically.
- D02 on functions with many parameters matters more than D04/D06 polish.
- Read the flagged code before writing docs; if a function is hard to describe in one sentence, say so: it may need splitting rather than a longer docstring.
- Check for docstrings that are present but useless ("Does the thing.", repeating the function name); the script cannot judge meaning, you can.

### 4. Plan the fix
Group work into small pull requests per module, starting with the public API. Propose the style from `references/docstring-styles.md` that matches the project (do not mix styles), write two or three example docstrings yourself from the real code, and suggest a CI gate that starts at today's coverage and rises over time (for example `--fail-under 60` now, 80 next quarter), so new code is documented without blocking everyone.

### 5. Report
Fill `templates/docstring-report.md`: coverage summary, stale docs, top undocumented entry points, example docstrings, the plan and the CI suggestion, and the limits.

## Example
```
python3 scripts/docstring_coverage.py examples/shipping_rates.py
python3 scripts/docstring_coverage.py examples/shipping_rates_documented.py --fail-under 90
```
The first run reports 37.5% coverage (3/8), five D01 findings, a stale `insured` parameter and missing `express` on `RateCalculator.quote` (D03, D02), plus missing Returns and an undocumented `ValueError`. The documented version passes with 100% and exit code 0.

## Limits
- Static analysis only: it cannot tell whether a docstring is correct or helpful, only whether it exists and matches the signature.
- Parameter sections are recognised in Google, NumPy and reST styles; unusual custom formats may produce false D02/D03 findings.
- Raises detection only sees direct `raise` statements in the function, not exceptions from called code.
- Properties, overloads and setters are skipped; dataclass fields are not checked individually.

FILE:references/docstring-styles.md
# Docstring styles

Pick one style per project and stick to it. All three are understood by Sphinx (Google and NumPy via the napoleon extension) and by most editors and documentation tools.

## Google style
Readable in plain text, compact, good default for applications and most libraries.

```python
def quote(parcel, zone, express=False):
    """Return the price for one parcel.

    Args:
        parcel: The parcel to ship.
        zone: One of the keys of ZONES.
        express: Whether express delivery is used.

    Returns:
        The price rounded to 2 decimals.

    Raises:
        ValueError: If the zone is unknown.
    """
```

## NumPy style
More vertical, popular in scientific Python (numpy, pandas, scipy). Good when types and shapes need explaining.

```python
def resample(values, factor):
    """Resample a series by an integer factor.

    Parameters
    ----------
    values : list of float
        Input samples.
    factor : int
        How many input samples make one output sample.

    Returns
    -------
    list of float
        The resampled series.
    """
```

## reST / Sphinx field style
Common in older projects and in Sphinx-first documentation.

```python
def connect(host, port=5432):
    """Open a database connection.

    :param host: Server host name.
    :param int port: Server port.
    :returns: An open connection.
    :raises ConnectionError: If the server cannot be reached.
    """
```

## How the script recognises them
- Parameter sections: `Args:`, `Arguments:`, `Parameters:`, `Keyword Args:`, `Other Parameters:` (Google), `Parameters` followed by a dashed line (NumPy), and `:param name:` / `:param type name:` (reST). `*args` and `**kwargs` may be written with or without stars.
- Returns: `Returns:`, `Return:`, `Yields:`, NumPy `Returns` / `Yields` headings, `:returns:`, `:rtype:`, `:yields:`.
- Raises: `Raises:` sections, `:raises X:` fields, or simply the exception name anywhere in the docstring.

## Choosing
| Situation | Suggested style |
|---|---|
| New application or internal library | Google |
| Scientific / data code with arrays and shapes | NumPy |
| Existing Sphinx docs already using fields | reST |
| Mixed project | the style most existing docstrings use; convert the rest gradually |

Type hints in the signature do not replace a docstring: they say what type a value is, the docstring says what it means, its units, defaults and edge cases. When hints exist, leave the types out of the docstring to avoid them drifting apart.

FILE:references/what-to-document.md
# What to document (and what not)

## A good docstring
1. **Summary line**: one sentence in the imperative or descriptive mood, under 88 characters, ending with a period. "Return the cheapest zone for a parcel." not "This function is used to get zone."
2. **Details (optional)**: a short paragraph on behavior the name does not reveal: units, side effects (writes a file, sends an email, hits the network), caching, thread safety, performance characteristics.
3. **Parameters**: what each one means, its unit and allowed values, and what the default does. Skip obvious type repetition when there are type hints.
4. **Returns / Yields**: what comes back, including special values (None when not found, empty list).
5. **Raises**: exceptions callers are expected to handle, and when.
6. **Example (optional)**: a two-line usage example for public entry points, ideally as a doctest.

## Leave out
- Restating the code line by line or the function name in other words.
- History ("changed in March to fix bug 123"): that belongs in git and the changelog.
- Implementation details that will change often; document the contract, not the internals.
- TODOs: track them as issues.

## Priorities when coverage is low
1. Stale docs (D03): wrong information is worse than none.
2. Public entry points used by other modules, services or users (what `__init__.py` exports, CLI commands, API handlers).
3. Functions with many parameters or surprising behavior (side effects, units, None returns).
4. Classes: one paragraph on what the object represents and its lifecycle.
5. Module docstrings: one or two sentences on what lives in the file.
6. Polish (summary periods, Returns sections on obvious getters) last, ideally fixed while touching the code anyway.

## Coverage targets
- Libraries published for others: 90-100% of the public API.
- Internal services: 70-85% of public functions and classes, 100% of anything other teams call.
- Scripts and glue code: module docstring plus the main entry point.
Ratchet the CI threshold up from today's number instead of jumping to a target that blocks every pull request.

## Writing with an AI assistant
Generated docstrings are a good first draft, but always check them against the code: assistants happily document parameters the function does not have, invent exceptions or describe what the name suggests instead of what the code does. Re-run the checker afterwards to catch stale parameters.

FILE:templates/docstring-report.md
# Docstring review: {project or package}

**Scanned:** {paths} on {date} - {files} files, {objects} public objects
**Style:** {Google | NumPy | reST | mixed}
**Command:** `python3 scripts/docstring_coverage.py {paths} {options}`

## Summary
- Coverage: **{pct}%** ({documented}/{objects}); modules {m}%, classes {c}%, functions {f}%, methods {me}%
- Stale docstrings (D03): {n}
- Undocumented public objects (D01): {n}, of which {k} are main entry points
- One-sentence verdict: {e.g. "Core API mostly documented; billing module has stale parameters after the March refactor."}

## Fix first: stale or wrong docs
| Location | Object | Problem | Fix |
|---|---|---|---|
| {file:line} | `{name}` | {documents `insured`, not in signature} | {remove or rename to `express`} |

## Top undocumented entry points
| Location | Object | Why it matters | Suggested summary line |
|---|---|---|---|
| {file:line} | `{name}` | {called from 6 modules / public API} | {Return the cheapest zone for a parcel.} |

## Example docstrings (from the real code)
```python
{2-3 complete docstrings in the chosen style}
```

## Plan
1. {PR 1:

출처 · prompts.chat 공개 프롬프트 모음 · 작성 Fatih Kadir Akın — CC0(저작권 포기)로 공개된 원문을 그대로 싣습니다. 한국어 제목 · 설명은 AI 번역이며, 실행 결과는 아직 없습니다.

같은 분야 프롬프트 에이전트 · 자동화

더 보기 ›