docstring-generator 1.0.2__tar.gz → 2.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,458 @@
1
+ Metadata-Version: 2.4
2
+ Name: docstring-generator
3
+ Version: 2.1.0
4
+ Summary: Auto generate docstring from type-hints.
5
+ Author: FelixTheC
6
+ Project-URL: Repository, https://github.com/FelixTheC/docstring_generator
7
+ Classifier: Environment :: Console
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Utilities
10
+ Classifier: Topic :: Software Development :: Documentation
11
+ Classifier: Typing :: Typed
12
+ Requires-Python: >=3.13
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: click==8.4.2
15
+ Requires-Dist: docstring-generator-ext>=2.0.4
16
+
17
+ [![Python 3.10](https://img.shields.io/badge/python-3-blue.svg)](https://www.python.org/downloads/)
18
+ [![PyPI version](https://badge.fury.io/py/docstring-generator.svg)](https://badge.fury.io/py/docstring-generator)
19
+ ![Actions](https://github.com/FelixTheC/docstring_generator/actions/workflows/python-app.yml/badge.svg)
20
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
21
+ [![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)
22
+ [![](https://img.shields.io/pypi/dm/docstring-generator.svg)](https://pypi.org/project/docstring-generator/)
23
+
24
+ # docstring_generator
25
+
26
+ > **Stop writing boilerplate docstrings by hand.** `docstring_generator` reads your type hints and generates professional, standards-compliant documentation in seconds — keeping your codebase clean, consistent, and AI-ready.
27
+
28
+ Python documentation tooling that automatically generates docstrings for functions and class methods from their type hints, with full support for **NumPy**, **Google**, and **reStructuredText** styles.
29
+
30
+ ---
31
+
32
+ ## Why docstring_generator?
33
+
34
+ Good documentation is no longer optional. AI coding assistants, static analysis tools, and auto-generated API docs all depend on structured, accurate docstrings. Yet writing them by hand is tedious, error-prone, and rarely kept up-to-date.
35
+
36
+ `docstring_generator` solves this by:
37
+
38
+ - ⚡ **Saving hours** — generate docs for an entire codebase in one command
39
+ - 🔄 **Staying in sync** — re-running only updates what changed in the function signature
40
+ - ✍️ **Preserving your words** — existing descriptions and custom notes are never overwritten
41
+ - 🧠 **AI-workflow friendly** — well-structured docstrings improve context quality for LLM-assisted development
42
+ - 🚨 **Exception-aware** — automatically detects `raise` statements and documents them in a `Raises` section, so failure modes are part of your API contract
43
+ - 🙈 **Convention-correct** — `self` and `cls` are automatically excluded from generated parameter sections, matching every major docstring standard
44
+ - ⚙️ **Async-ready** — handles both `def` and `async def` functions transparently, no extra configuration needed
45
+ - 🎨 **Style-safe** — detects the existing docstring style and refuses to silently mix conventions; explicit opt-in required to convert styles
46
+ - 🏎️ **Blazing fast** — core engine written in C++ via [pybind11](https://github.com/FelixTheC/docstring_generator_ext)
47
+
48
+ ---
49
+
50
+ ## Quick Start
51
+
52
+ One command. Any file or directory:
53
+
54
+ ```shell
55
+ pip install docstring-generator
56
+ ```
57
+
58
+ ```shell
59
+ gendocs_new file.py # single file
60
+ gendocs_new mydir/ # entire directory
61
+ ```
62
+
63
+ That's it. Your functions now have properly formatted docstrings.
64
+
65
+ ---
66
+
67
+ ## Options
68
+
69
+ ### `--style` — Choose your docstring convention
70
+
71
+ | Style | Flag | Description |
72
+ |-------|------|-------------|
73
+ | NumPy | `--style numpy` | Standard in scientific Python (default) |
74
+ | Google | `--style google` | Preferred in many enterprise codebases |
75
+ | reStructuredText | `--style rest` | Compatible with Sphinx auto-documentation |
76
+
77
+ **Default:** `numpy`
78
+
79
+ ### `--check` — Docstring coverage report
80
+
81
+ Scan a file or directory and get a coverage overview without modifying anything:
82
+
83
+ ```shell
84
+ gendocs_new mydir/ --check
85
+ ```
86
+
87
+ Outputs a per-file summary showing which functions are documented and which are missing docstrings.
88
+
89
+ ### `--strict` — Treat partial docstrings as missing
90
+
91
+ By default, a function with any docstring counts as documented. Strict mode raises the bar:
92
+
93
+ ```shell
94
+ gendocs_new mydir/ --check --strict
95
+ ```
96
+
97
+ A partial docstring (e.g. missing parameter sections) is treated as undocumented in strict mode.
98
+
99
+ ### `--threshold` — Enforce a minimum coverage percentage
100
+
101
+ Fail the check if coverage drops below a given percentage (0–100):
102
+
103
+ ```shell
104
+ gendocs_new mydir/ --check --threshold 80
105
+ ```
106
+
107
+ Useful in CI pipelines to enforce documentation standards across the codebase.
108
+
109
+ ### `--exclude-file` — Skip specific files
110
+
111
+ Exclude one or more files from processing by name. Can be passed multiple times:
112
+
113
+ ```shell
114
+ gendocs_new mydir/ --exclude-file conftest.py --exclude-file settings.py
115
+ ```
116
+
117
+ Files whose name matches any of the provided values are skipped during docstring generation.
118
+
119
+ ### `--exclude-dir` — Skip specific directories
120
+
121
+ Exclude one or more directories from processing. Can be passed multiple times:
122
+
123
+ ```shell
124
+ gendocs_new mydir/ --exclude-dir tests --exclude-dir migrations
125
+ ```
126
+
127
+ Any file whose path contains one of the given directory names is skipped.
128
+
129
+ ### `--dry-run` — Preview changes without modifying any file
130
+
131
+ Run the generator in read-only mode and see exactly what would be added or changed as a unified diff:
132
+
133
+ ```shell
134
+ gendocs_new mydir/ --dry-run
135
+ ```
136
+
137
+ Files that already have complete docstrings print `<file>: no changes`. Files with missing docstrings show a `+`/`-` diff so you can review before committing. Combine with `--style` or `--overwrite-style` to preview a style migration:
138
+
139
+ ```shell
140
+ gendocs_new mydir/ --style google --overwrite-style --dry-run
141
+ ```
142
+
143
+ ### `--changed-only` — Only process git-changed files
144
+
145
+ Restrict processing to files that are modified or staged in git — perfect for large repos where running on the full `src/` directory on every commit would be slow:
146
+
147
+ ```shell
148
+ gendocs_new mydir/ --changed-only
149
+ ```
150
+
151
+ Internally runs `git diff --name-only HEAD` and `git diff --cached --name-only` to collect the list of changed and staged `.py` files, then intersects that list with the paths you provided. If git is not installed or not available on `PATH`, the command aborts immediately with a clear error message rather than silently processing everything.
152
+
153
+ Combines well with `--dry-run` to preview what *would* change for only the files you touched:
154
+
155
+ ```shell
156
+ gendocs_new mydir/ --changed-only --dry-run
157
+ ```
158
+
159
+ ### `--ignore-magic` — Skip dunder / magic methods
160
+
161
+ Exclude dunder methods such as `__init__`, `__str__`, `__repr__`, `__eq__`, etc. from docstring generation. These are often implementation details that add noise rather than value to public documentation:
162
+
163
+ ```shell
164
+ gendocs_new mydir/ --ignore-magic
165
+ ```
166
+
167
+ Can also be enabled permanently via `pyproject.toml` so every invocation skips magic methods without an explicit flag:
168
+
169
+ ```toml
170
+ [tool.docstring_generator]
171
+ ignore_magic = true
172
+ ```
173
+
174
+ ### `--overwrite-style` — Re-format existing docstrings in a different style
175
+
176
+ Force regeneration of existing docstrings using the specified style, even if they already have content:
177
+
178
+ ```shell
179
+ gendocs_new mydir/ --style google --overwrite-style true
180
+ ```
181
+
182
+ Useful when migrating a codebase from one docstring convention to another.
183
+
184
+ ---
185
+
186
+ ## Configuration via `pyproject.toml`
187
+
188
+ Instead of passing flags on every invocation, persist defaults in your project's `pyproject.toml` under the `[tool.docstring_generator]` namespace:
189
+
190
+ ```toml
191
+ [tool.docstring_generator]
192
+ strict = true
193
+ threshold = 90
194
+ exclude_files = ["conftest.py", "settings.py"]
195
+ exclude_dirs = ["tests", "migrations"]
196
+ ignore_magic = true
197
+ ```
198
+
199
+ CLI flags always override `pyproject.toml` values. The tool automatically walks up from the target path to find the nearest `pyproject.toml`.
200
+
201
+ ---
202
+
203
+ ## Preserve Custom Descriptions with `$<num>` Placeholders
204
+
205
+ Write your domain-specific notes once — `docstring_generator` will place them in the right parameter slot automatically.
206
+
207
+ Use `$1`, `$2`, … in your docstring body to map descriptions to positional parameters:
208
+
209
+ ```python
210
+ from typing import List
211
+
212
+
213
+ def foo(val_a: int, val_b: List[int]):
214
+ """
215
+ Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
216
+ sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam
217
+
218
+ $1 Lorem ipsum dolor sit amet
219
+ $2 nonumy eirmod tempor invidun
220
+ """
221
+ ```
222
+
223
+ After running `gendocs_new` (NumPy style):
224
+
225
+ ```python
226
+ from typing import List
227
+
228
+
229
+ def foo(val_a: int, val_b: List[int]):
230
+ """
231
+ Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
232
+ sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam
233
+
234
+ Parameters
235
+ ----------
236
+ val_a : argument of type int
237
+ Lorem ipsum dolor sit amet
238
+ val_b : argument of type List(int)
239
+ nonumy eirmod tempor invidun
240
+
241
+ """
242
+ ```
243
+
244
+ ---
245
+
246
+ ## Preserve Return Description with `>>` Marker
247
+
248
+ Use `>>` on its own line inside an existing docstring to provide a description for the return value. On the next `gendocs_new` run the marker is consumed and wired into the `Returns` section automatically.
249
+
250
+ ```python
251
+ def square(x: int) -> int:
252
+ """Square a number.
253
+
254
+ >> The squared value of x.
255
+ """
256
+ return x * x
257
+ ```
258
+
259
+ After running `gendocs_new` (Google style):
260
+
261
+ ```python
262
+ def square(x: int) -> int:
263
+ """Square a number.
264
+
265
+ Args:
266
+ x (int):
267
+ Returns:
268
+ int: The squared value of x.
269
+ """
270
+ return x * x
271
+ ```
272
+
273
+ Combine `$N` for parameter descriptions and `>>` for the return description to fully annotate a function before running the generator — no manual editing of the structured sections needed.
274
+
275
+ ---
276
+
277
+ ## Automatic `Raises` Extraction
278
+
279
+ `docstring_generator` statically analyzes your function body for `raise` statements and adds a `Raises` section describing each exception — including the condition that triggers it. This works seamlessly with frameworks like **Pydantic**, **FastAPI**, or any custom validation logic.
280
+
281
+ ### Before
282
+
283
+ ```python
284
+ class PluginConfig(BaseModel):
285
+ name: str = Field(default="default")
286
+ api_config: dict = Field(default_factory=dict)
287
+
288
+ @field_validator("api_config", mode='before')
289
+ @classmethod
290
+ def validate_api_config(cls, values: dict) -> dict:
291
+ required_key_obj = values.get("required_keys", None)
292
+ if not required_key_obj:
293
+ raise ValueError("The first key must be 'required_keys'")
294
+ if not isinstance(required_key_obj, dict):
295
+ raise ValueError("The 'required_keys' must be a dict")
296
+ return values
297
+ ```
298
+
299
+ ### After running `gendocs_new`
300
+
301
+ ```python
302
+ class PluginConfig(BaseModel):
303
+ name: str = Field(default="default")
304
+ api_config: dict = Field(default_factory=dict)
305
+
306
+ @field_validator("api_config", mode='before')
307
+ @classmethod
308
+ def validate_api_config(cls, values: dict) -> dict:
309
+ """
310
+ Parameters
311
+ ----------
312
+ values : dict [Argument]
313
+
314
+ Returns
315
+ -------
316
+ dict
317
+
318
+ Raises
319
+ -------
320
+ ValueError
321
+ If not isinstance(required_key_obj, dict)
322
+ ValueError
323
+ If not required_key_obj
324
+ """
325
+ required_key_obj = values.get("required_keys", None)
326
+ if not required_key_obj:
327
+ raise ValueError("The first key must be 'required_keys'")
328
+ if not isinstance(required_key_obj, dict):
329
+ raise ValueError("The 'required_keys' must be a dict")
330
+ return values
331
+ ```
332
+
333
+ Every `raise` — even multiple ones in the same function — is captured, so complex validators document all their failure modes at once.
334
+
335
+ No more hunting through code to find out what a function can throw — it's documented right where it matters.
336
+
337
+ ---
338
+
339
+ ## Pre-commit Integration
340
+
341
+ Automatically generate docstrings on every commit using the [pre-commit](https://pre-commit.com/) framework.
342
+
343
+ ### Setup
344
+
345
+ Add this to your project's `.pre-commit-config.yaml`:
346
+
347
+ ```yaml
348
+ repos:
349
+ - repo: https://github.com/FelixTheC/docstring_generator
350
+ rev: v0.3.4 # pin to a release tag
351
+ hooks:
352
+ - id: gendocs
353
+ args: [src/] # directory to process
354
+ ```
355
+
356
+ Install the hook:
357
+
358
+ ```shell
359
+ pip install pre-commit
360
+ pre-commit install
361
+ ```
362
+
363
+ ### How it works
364
+
365
+ The hook runs `gendocs_new` before each commit. If it generates or updates any docstrings, the commit is intentionally stopped so you can review and stage the changes:
366
+
367
+ | Run | What happens | Status |
368
+ |-----|-------------|--------|
369
+ | 1st commit | Hook generates docstrings → files modified | ❌ Stopped (intentional) |
370
+ | `git add` modified files | Stage the generated docstrings | — |
371
+ | 2nd commit | Hook runs, nothing changed | ✅ Passed |
372
+
373
+ This is standard behavior for any auto-fix hook (same as Black or isort).
374
+
375
+ ### Customizing the style
376
+
377
+ ```yaml
378
+ hooks:
379
+ - id: gendocs
380
+ args: [src/, --style, google]
381
+ ```
382
+
383
+ ---
384
+
385
+ ## FAQ
386
+
387
+ ### What happens if I re-run docstring generation?
388
+
389
+ Nothing is lost. If the function signature hasn't changed, the existing docstring stays untouched. If you add or rename parameters, only the structural part is updated — your custom descriptions are preserved.
390
+
391
+ ### Is it safe to use on an existing codebase?
392
+
393
+ Yes. The tool is non-destructive by design. It never deletes content; it only adds or updates parameter sections based on type hints.
394
+
395
+ ### Does it work with class methods?
396
+
397
+ Yes — both standalone functions and class methods are fully supported.
398
+
399
+ ---
400
+
401
+ ## Examples
402
+
403
+ Ready-to-run examples are available in the [`examples/`](examples/) directory.
404
+
405
+ ---
406
+
407
+ ## Installation
408
+
409
+ ```shell
410
+ pip install docstring-generator
411
+ ```
412
+
413
+ Requires Python 3.13+.
414
+
415
+ ---
416
+
417
+ ## How It Works
418
+
419
+ The core engine is implemented in C++ (C++20) and exposed to Python via [pybind11](https://github.com/pybind/pybind11), delivering performance that scales to large codebases without slowing down your workflow.
420
+
421
+ - **Extension:** [docstring-generator-ext](https://github.com/FelixTheC/docstring_generator_ext) — the high-performance backbone of this project
422
+
423
+ ---
424
+
425
+ ## Roadmap
426
+
427
+ Planned features and areas of investment:
428
+
429
+ ### Medium-term
430
+
431
+ - [ ] GitHub Action — publish a ready-to-use Action to the Marketplace so teams can enforce docstring coverage in CI without any local installation
432
+ - [ ] Coverage badge generation (`--badge`) — produce an SVG badge from `--check` results to embed in README, similar to a test-coverage badge
433
+ - [ ] JUnit/SARIF output for `--check` — emit machine-readable results for GitHub, GitLab, and Azure DevOps CI panels; enables PR annotations that highlight undocumented functions inline
434
+ - [ ] IDE plugin support (JetBrains, VS Code)
435
+
436
+ ### Longer-term
437
+
438
+ - [ ] Watch mode (`--watch`) — monitor the project for file saves and regenerate docstrings automatically in the background
439
+ - [ ] Sphinx / mkdocs bridge (`--export-rst`) — generate `.rst` or `.md` stubs ready for Sphinx/mkdocs autodoc pipelines
440
+ - [ ] Custom docstring templates — let teams define their own format via `pyproject.toml` for internal style guides that extend NumPy or Google
441
+ - [ ] LLM-assisted description generation (opt-in enrichment mode) — use a local or remote LLM to fill in meaningful parameter descriptions beyond the type hint
442
+ - [ ] CI/CD pipeline gate (fail build below coverage threshold)
443
+
444
+ Community feedback shapes priorities — open an issue to vote on features or suggest new ones.
445
+
446
+ ---
447
+
448
+ ## Versioning
449
+
450
+ Follows [Semantic Versioning](https://semver.org/). See the [tags](../../tags) for all available releases.
451
+
452
+ ## Authors
453
+
454
+ - **Felix Eisenmenger** — creator & maintainer
455
+
456
+ ## License
457
+
458
+ MIT License — free to use in personal and commercial projects.