Documentation Writer
Overview
The Documentation Writer skill produces clear, accurate, and maintainable technical documentation across all layers: project-level READMEs, module-level docstrings, function-level API docs, and inline code comments. It covers the standard formats for multiple languages (JSDoc, Python docstrings in Google/NumPy/Sphinx style, GoDoc), README structure best practices, CHANGELOG format (Keep a Changelog), and principles for writing comments that add value rather than noise. Good documentation is part of the code — it reduces onboarding time, prevents misuse, and serves as a contract with consumers.
When to Use
- Writing a README for a new library, tool, or service
- Adding docstrings to functions, classes, or modules
- Documenting a public API for external or internal consumers
- Writing or updating a CHANGELOG when releasing a new version
- Adding inline comments to explain non-obvious logic
When NOT to Use
- Writing user-facing help docs or tutorials (different audience and tone)
- Writing blog posts or marketing copy
- Generating API reference docs from non-annotated code (annotate first, then generate)
- Writing architectural decisions (use the architecture-designer skill for ADRs)
Quick Reference
| Doc Type |
Purpose |
Format |
| README |
Project overview, quickstart, usage |
Markdown with badges, code blocks, TOC |
| Docstring (Python) |
Function/class contract |
Google, NumPy, or Sphinx style |
| JSDoc |
JS/TS function/class docs |
/** @param @returns @throws */ |
| GoDoc |
Go package/function docs |
Plain comment above declaration |
| Inline comment |
Explain why, not what |
Sparingly; 1-2 lines |
| CHANGELOG |
User-facing change history |
Keep a Changelog format |
| OpenAPI |
REST API reference |
YAML/JSON, generated from annotations |
Instructions
Know your audience
- README: New users who need to evaluate, install, and get started quickly.
- Docstrings: Developers who will call your function — they need to know the contract (parameters, return values, exceptions, side effects), not the implementation.
- Inline comments: The developer maintaining this code 6 months from now (possibly you).
- CHANGELOG: Users upgrading — they need to know what changed and if they need to do anything.
Write the README with this structure
1. Project name + one-line tagline
2. Badges (CI, coverage, version, license)
3. Short description (2-3 sentences, why does this exist?)
4. Quick Start / Installation (fewest steps to get running)
5. Usage with code examples
6. Configuration reference
7. API reference (or link to generated docs)
8. Contributing guide
9. License
Write docstrings for every public function, class, and module
- Describe what it does, not how (don't repeat the code).
- Document every parameter with type and description.
- Document the return value with type and description.
- Document every exception that can be raised and when.
- Include a usage example for non-trivial functions.
Write inline comments that explain why, not what
- Bad:
i += 1 # increment i (the code already says this)
- Good:
# Skip the header row — it's not data
- Good:
# Retry up to 3 times to handle transient network errors
- Comment non-obvious algorithms, workarounds, and performance-critical decisions.
Maintain the CHANGELOG
- Follow Keep a Changelog:
Added, Changed, Deprecated, Removed, Fixed, Security.
- Each release has a version number and date.
- Write from the user's perspective: "what changed for me?" not "what did we do?"
Review and update docs with code changes
- Treat outdated documentation as a bug.
- Update docstrings when function signatures, behavior, or exceptions change.
- Update the README when installation steps, config options, or usage patterns change.
Examples
Example 1: Write a README for an open-source Python library
Input: "Write a README for quickcache, a Python library that provides a simple decorator for caching function results with TTL support."
Output:
# quickcache
[](https://github.com/example/quickcache/actions)
[](https://pypi.org/project/quickcache/)
[](https://codecov.io/gh/example/quickcache)
[](LICENSE)
A simple, zero-dependency Python decorator for caching function results with optional time-to-live (TTL) expiration. Stop re-computing expensive results on every call.
## Quick Start
```bash
pip install quickcache
```
```python
from quickcache import cache
@cache(ttl=60) # Cache for 60 seconds
def get_user(user_id: int) -> dict:
return database.fetch_user(user_id)
user = get_user(42) # Hits the database
user = get_user(42) # Returns cached result instantly
```
## Features
- ✅ Simple decorator API
- ✅ Configurable TTL (time-to-live) per function
- ✅ Supports sync and async functions
- ✅ Thread-safe in-memory cache
- ✅ Optional Redis backend for distributed caching
- ✅ Zero dependencies (in-memory mode)
## Installation
```bash
pip install quickcache # In-memory caching (zero dependencies)
pip install quickcache[redis] # Redis backend
```
## Usage
### Basic caching
```python
from quickcache import cache
@cache()
def expensive_computation(x: int, y: int) -> int:
"""Cached with no TTL — cached until process restarts."""
return x ** y
```
### With TTL
```python
@cache(ttl=300) # Cache for 5 minutes
def fetch_exchange_rate(currency: str) -> float:
return api.get_rate(currency)
```
### Async support
```python
@cache(ttl=60)
async def fetch_user_async(user_id: int) -> dict:
return await db.fetch_user(user_id)
```
### Redis backend (distributed)
```python
from quickcache import cache
from quickcache.backends import RedisBackend
backend = RedisBackend(host='localhost', port=6379, db=0)
@cache(ttl=120, backend=backend)
def get_product(product_id: int) -> dict:
return db.fetch_product(product_id)
```
### Cache invalidation
```python
from quickcache import cache, invalidate
@cache(ttl=60, key='user:{user_id}')
def get_user(user_id: int) -> dict:
return db.fetch_user(user_id)
# Invalidate a specific user's cache
invalidate('user:42')
# Invalidate by function
get_user.invalidate(42)
# Clear all cache
get_user.clear()
```
## Configuration
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `ttl` | `int \| None` | `None` | Seconds before cache entry expires. `None` = never expires. |
| `backend` | `Backend` | `MemoryBackend()` | Cache backend instance. |
| `key` | `str \| None` | Auto | Cache key template. Use `{param_name}` for dynamic keys. |
| `maxsize` | `int` | `1024` | Max entries for in-memory backend (LRU eviction). |
## Contributing
Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup, coding standards, and pull request process.
```bash
git clone https://github.com/example/quickcache.git
cd quickcache
pip install -e ".[dev]"
pytest
```
## License
MIT — see [LICENSE](LICENSE).
Example 2: Document a Python module with docstrings
Input: A Python module to document:
import re
from typing import Optional
def validate_email(email, strict=False):
pattern = r'^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$'
if strict:
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email, re.IGNORECASE))
def normalize_email(email):
local, domain = email.rsplit('@', 1)
local = local.split('+')[0]
return f"{local.lower()}@{domain.lower()}"
class EmailValidator:
def __init__(self, allowed_domains=None):
self.allowed_domains = set(allowed_domains or [])
def is_valid(self, email):
if not validate_email(email):
return False
if self.allowed_domains:
domain = email.rsplit('@', 1)[1].lower()
return domain in self.allowed_domains
return True
Output (with Google-style docstrings):
"""Email validation and normalization utilities.
This module provides functions and a class for validating and normalizing
email addresses. It supports basic RFC-compliant validation, strict mode
for stricter character rules, and domain allowlisting.
Typical usage::
from email_utils import validate_email, normalize_email, EmailValidator
if validate_email("alice@example.com"):
canonical = normalize_email("Alice+tag@Example.COM")
# canonical == "alice@example.com"
validator = EmailValidator(allowed_domains=["company.com"])
validator.is_valid("alice@company.com") # True
validator.is_valid("alice@gmail.com") # False
"""
import re
from typing import Optional
def validate_email(email: str, strict: bool = False) -> bool:
"""Validate whether a string is a well-formed email address.
Uses a regex pattern to check that the email has a valid local part,
an @ symbol, a domain, and a TLD of at least 2 characters. Strict mode
disallows some special characters (e.g., `!`, `#`) in the local part.
Args:
email: The email address string to validate.
strict: If True, applies stricter character rules in the local part
(only alphanumeric, dots, underscores, percent, plus, hyphen).
Defaults to False.
Returns:
True if the email matches the pattern; False otherwise.
Examples:
>>> validate_email("alice@example.com")
True
>>> validate_email("not-an-email")
False
>>> validate_email("alice!@example.com", strict=True)
False
"""
pattern = r'^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$'
if strict:
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email, re.IGNORECASE))
def normalize_email(email: str) -> str:
"""Normalize an email address to its canonical form.
Strips the plus-addressing suffix from the local part and lowercases
both the local part and the domain. This enables deduplication of
addresses like ``Alice+newsletter@Example.COM`` and ``alice@example.com``.
Note:
This function does not validate the email. Call ``validate_email``
first if you need to ensure the input is well-formed.
Args:
email: A well-formed email address string.
Returns:
The normalized email address in lowercase with plus-addressing removed.
Raises:
ValueError: If the email does not contain an ``@`` symbol.
Examples:
>>> normalize_email("Alice+tag@Example.COM")
'alice@example.com'
>>> normalize_email("BOB@COMPANY.ORG")
'bob@company.org'
"""
if '@' not in email:
raise ValueError(f"Invalid email address (missing @): {email!r}")
local, domain = email.rsplit('@', 1)
local = local.split('+')[0]
return f"{local.lower()}@{domain.lower()}"
class EmailValidator:
"""Validates email addresses with optional domain allowlisting.
Combines format validation with domain restriction. Useful for
ensuring that only users with addresses from specific domains
(e.g., corporate email) can register.
Attributes:
allowed_domains: A set of lowercase domain strings that are
permitted. Empty set means all domains are allowed.
Example:
>>> validator = EmailValidator(allowed_domains=["company.com", "company.org"])
>>> validator.is_valid("alice@company.com")
True
>>> validator.is_valid("bob@gmail.com")
False
>>> open_validator = EmailValidator()
>>> open_validator.is_valid("anyone@anywhere.io")
True
"""
def __init__(self, allowed_domains: Optional[list[str]] = None) -> None:
"""Initialize the validator with an optional domain allowlist.
Args:
allowed_domains: A list of permitted email domains (case-insensitive).
If None or empty, all domains are allowed.
"""
self.allowed_domains = {d.lower() for d in (allowed_domains or [])}
def is_valid(self, email: str) -> bool:
"""Check whether an email address is valid and from an allowed domain.
Args:
email: The email address to validate.
Returns:
True if the email passes format validation and (if configured)
its domain is in the allowlist. False otherwise.
"""
if not validate_email(email):
return False
if self.allowed_domains:
domain = email.rsplit('@', 1)[1].lower()
return domain in self.allowed_domains
return True
JSDoc equivalent (TypeScript):
/**
* Validates whether a string is a well-formed email address.
*
* @param email - The email address string to validate.
* @param strict - If true, applies stricter character rules in the local part.
* @returns `true` if the email matches the expected pattern; `false` otherwise.
*
* @example
* ```ts
* validateEmail("alice@example.com"); // true
* validateEmail("not-an-email"); // false
* validateEmail("alice!@example.com", true); // false (strict mode)
* ```
*/
export function validateEmail(email: string, strict = false): boolean {
const pattern = strict
? /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/i
: /^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$/i;
return pattern.test(email);
}
GoDoc equivalent:
// Package email provides utilities for validating and normalizing email addresses.
//
// Example usage:
//
// if email.IsValid("alice@example.com") {
// canonical := email.Normalize("Alice+tag@Example.COM")
// fmt.Println(canonical) // alice@example.com
// }
package email
// IsValid reports whether s is a well-formed email address.
// It uses a regex-based heuristic and is suitable for most real-world
// validation purposes. For strict RFC 5321 compliance, use IsValidStrict.
func IsValid(s string) bool { ... }
// Normalize returns the canonical form of the email address by lowercasing
// both the local part and domain, and stripping any plus-addressing suffix
// (e.g., "Alice+tag@Example.COM" → "alice@example.com").
//
// Normalize does not validate the email. Call IsValid first if needed.
func Normalize(s string) (string, error) { ... }
Best Practices
- Write docs before or alongside code, not as an afterthought
- Keep docs close to the code they describe — co-located docstrings beat separate wiki pages
- Treat documentation as code: review it in PRs, update it with behavior changes
- Use examples liberally — a usage example is worth more than three paragraphs of prose
- Make the first sentence of a docstring a complete, standalone description (it appears in IDE tooltips and auto-generated indexes)
Common Mistakes
- Restating what the code does ("This function increments x by 1") instead of explaining purpose and contract
- Documenting parameters without types or units (is
timeout in ms or seconds?)
- Outdated docs that contradict the current behavior — worse than no docs
- Missing exception documentation — callers can't handle errors they don't know about
- Documenting private/internal implementation details that may change vs. the stable public API
Tips & Tricks
pydoc, sphinx, typedoc, and godoc generate HTML API references from docstrings automatically
- Keep a Changelog (keepachangelog.com) is the standard CHANGELOG format — follow it consistently
- Use
# TODO(username): reason format for deferred work so it's trackable
- Add examples to docstrings that are also run as doctests in Python:
pytest --doctest-modules
- Badge generators: shields.io creates badges for README (CI status, version, license, coverage)
Related Skills
1---2name: documentation-writer3description: "Use this skill when writing or improving technical documentation including READMEs, docstrings, API docs, changelogs, or inline code comments. Trigger phrases: 'write a README', 'document this function', 'add docstrings', 'improve the docs'. Not for writing blog posts, marketing copy, or user-facing help articles."4version: 1.0.05author: community6tags: [coding, documentation, readme, docstrings, comments]7license: MIT8metadata:9 source: https://skillmd.com/skills/xcrrr/documentation-writer10---1112# Documentation Writer1314## Overview15The Documentation Writer skill produces clear, accurate, and maintainable technical documentation across all layers: project-level READMEs, module-level docstrings, function-level API docs, and inline code comments. It covers the standard formats for multiple languages (JSDoc, Python docstrings in Google/NumPy/Sphinx style, GoDoc), README structure best practices, CHANGELOG format (Keep a Changelog), and principles for writing comments that add value rather than noise. Good documentation is part of the code — it reduces onboarding time, prevents misuse, and serves as a contract with consumers.1617## When to Use18- Writing a README for a new library, tool, or service19- Adding docstrings to functions, classes, or modules20- Documenting a public API for external or internal consumers21- Writing or updating a CHANGELOG when releasing a new version22- Adding inline comments to explain non-obvious logic2324## When NOT to Use25- Writing user-facing help docs or tutorials (different audience and tone)26- Writing blog posts or marketing copy27- Generating API reference docs from non-annotated code (annotate first, then generate)28- Writing architectural decisions (use the architecture-designer skill for ADRs)2930## Quick Reference31| Doc Type | Purpose | Format |32|----------|---------|--------|33| README | Project overview, quickstart, usage | Markdown with badges, code blocks, TOC |34| Docstring (Python) | Function/class contract | Google, NumPy, or Sphinx style |35| JSDoc | JS/TS function/class docs | `/** @param @returns @throws */` |36| GoDoc | Go package/function docs | Plain comment above declaration |37| Inline comment | Explain *why*, not *what* | Sparingly; 1-2 lines |38| CHANGELOG | User-facing change history | Keep a Changelog format |39| OpenAPI | REST API reference | YAML/JSON, generated from annotations |4041## Instructions42431. **Know your audience**44 - **README**: New users who need to evaluate, install, and get started quickly.45 - **Docstrings**: Developers who will call your function — they need to know the contract (parameters, return values, exceptions, side effects), not the implementation.46 - **Inline comments**: The developer maintaining this code 6 months from now (possibly you).47 - **CHANGELOG**: Users upgrading — they need to know what changed and if they need to do anything.48492. **Write the README with this structure**50 ```51 1. Project name + one-line tagline52 2. Badges (CI, coverage, version, license)53 3. Short description (2-3 sentences, why does this exist?)54 4. Quick Start / Installation (fewest steps to get running)55 5. Usage with code examples56 6. Configuration reference57 7. API reference (or link to generated docs)58 8. Contributing guide59 9. License60 ```61623. **Write docstrings for every public function, class, and module**63 - Describe *what* it does, not *how* (don't repeat the code).64 - Document every parameter with type and description.65 - Document the return value with type and description.66 - Document every exception that can be raised and when.67 - Include a usage example for non-trivial functions.68694. **Write inline comments that explain *why*, not *what***70 - Bad: `i += 1 # increment i` (the code already says this)71 - Good: `# Skip the header row — it's not data`72 - Good: `# Retry up to 3 times to handle transient network errors`73 - Comment non-obvious algorithms, workarounds, and performance-critical decisions.74755. **Maintain the CHANGELOG**76 - Follow Keep a Changelog: `Added`, `Changed`, `Deprecated`, `Removed`, `Fixed`, `Security`.77 - Each release has a version number and date.78 - Write from the user's perspective: "what changed for me?" not "what did we do?"79806. **Review and update docs with code changes**81 - Treat outdated documentation as a bug.82 - Update docstrings when function signatures, behavior, or exceptions change.83 - Update the README when installation steps, config options, or usage patterns change.8485## Examples8687### Example 1: Write a README for an open-source Python library8889**Input:** "Write a README for `quickcache`, a Python library that provides a simple decorator for caching function results with TTL support."9091**Output:**9293````markdown94# quickcache9596[](https://github.com/example/quickcache/actions)97[](https://pypi.org/project/quickcache/)98[](https://codecov.io/gh/example/quickcache)99[](LICENSE)100101A simple, zero-dependency Python decorator for caching function results with optional time-to-live (TTL) expiration. Stop re-computing expensive results on every call.102103## Quick Start104105```bash106pip install quickcache107```108109```python110from quickcache import cache111112@cache(ttl=60) # Cache for 60 seconds113def get_user(user_id: int) -> dict:114 return database.fetch_user(user_id)115116user = get_user(42) # Hits the database117user = get_user(42) # Returns cached result instantly118```119120## Features121122- ✅ Simple decorator API123- ✅ Configurable TTL (time-to-live) per function124- ✅ Supports sync and async functions125- ✅ Thread-safe in-memory cache126- ✅ Optional Redis backend for distributed caching127- ✅ Zero dependencies (in-memory mode)128129## Installation130131```bash132pip install quickcache # In-memory caching (zero dependencies)133pip install quickcache[redis] # Redis backend134```135136## Usage137138### Basic caching139140```python141from quickcache import cache142143@cache()144def expensive_computation(x: int, y: int) -> int:145 """Cached with no TTL — cached until process restarts."""146 return x ** y147```148149### With TTL150151```python152@cache(ttl=300) # Cache for 5 minutes153def fetch_exchange_rate(currency: str) -> float:154 return api.get_rate(currency)155```156157### Async support158159```python160@cache(ttl=60)161async def fetch_user_async(user_id: int) -> dict:162 return await db.fetch_user(user_id)163```164165### Redis backend (distributed)166167```python168from quickcache import cache169from quickcache.backends import RedisBackend170171backend = RedisBackend(host='localhost', port=6379, db=0)172173@cache(ttl=120, backend=backend)174def get_product(product_id: int) -> dict:175 return db.fetch_product(product_id)176```177178### Cache invalidation179180```python181from quickcache import cache, invalidate182183@cache(ttl=60, key='user:{user_id}')184def get_user(user_id: int) -> dict:185 return db.fetch_user(user_id)186187# Invalidate a specific user's cache188invalidate('user:42')189190# Invalidate by function191get_user.invalidate(42)192193# Clear all cache194get_user.clear()195```196197## Configuration198199| Parameter | Type | Default | Description |200|-----------|------|---------|-------------|201| `ttl` | `int \| None` | `None` | Seconds before cache entry expires. `None` = never expires. |202| `backend` | `Backend` | `MemoryBackend()` | Cache backend instance. |203| `key` | `str \| None` | Auto | Cache key template. Use `{param_name}` for dynamic keys. |204| `maxsize` | `int` | `1024` | Max entries for in-memory backend (LRU eviction). |205206## Contributing207208Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup, coding standards, and pull request process.209210```bash211git clone https://github.com/example/quickcache.git212cd quickcache213pip install -e ".[dev]"214pytest215```216217## License218219MIT — see [LICENSE](LICENSE).220````221222---223224### Example 2: Document a Python module with docstrings225226**Input:** A Python module to document:227```python228import re229from typing import Optional230231def validate_email(email, strict=False):232 pattern = r'^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$'233 if strict:234 pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'235 return bool(re.match(pattern, email, re.IGNORECASE))236237def normalize_email(email):238 local, domain = email.rsplit('@', 1)239 local = local.split('+')[0]240 return f"{local.lower()}@{domain.lower()}"241242class EmailValidator:243 def __init__(self, allowed_domains=None):244 self.allowed_domains = set(allowed_domains or [])245246 def is_valid(self, email):247 if not validate_email(email):248 return False249 if self.allowed_domains:250 domain = email.rsplit('@', 1)[1].lower()251 return domain in self.allowed_domains252 return True253```254255**Output (with Google-style docstrings):**256```python257"""Email validation and normalization utilities.258259This module provides functions and a class for validating and normalizing260email addresses. It supports basic RFC-compliant validation, strict mode261for stricter character rules, and domain allowlisting.262263Typical usage::264265 from email_utils import validate_email, normalize_email, EmailValidator266267 if validate_email("alice@example.com"):268 canonical = normalize_email("Alice+tag@Example.COM")269 # canonical == "alice@example.com"270271 validator = EmailValidator(allowed_domains=["company.com"])272 validator.is_valid("alice@company.com") # True273 validator.is_valid("alice@gmail.com") # False274"""275276import re277from typing import Optional278279280def validate_email(email: str, strict: bool = False) -> bool:281 """Validate whether a string is a well-formed email address.282283 Uses a regex pattern to check that the email has a valid local part,284 an @ symbol, a domain, and a TLD of at least 2 characters. Strict mode285 disallows some special characters (e.g., `!`, `#`) in the local part.286287 Args:288 email: The email address string to validate.289 strict: If True, applies stricter character rules in the local part290 (only alphanumeric, dots, underscores, percent, plus, hyphen).291 Defaults to False.292293 Returns:294 True if the email matches the pattern; False otherwise.295296 Examples:297 >>> validate_email("alice@example.com")298 True299 >>> validate_email("not-an-email")300 False301 >>> validate_email("alice!@example.com", strict=True)302 False303 """304 pattern = r'^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$'305 if strict:306 pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'307 return bool(re.match(pattern, email, re.IGNORECASE))308309310def normalize_email(email: str) -> str:311 """Normalize an email address to its canonical form.312313 Strips the plus-addressing suffix from the local part and lowercases314 both the local part and the domain. This enables deduplication of315 addresses like ``Alice+newsletter@Example.COM`` and ``alice@example.com``.316317 Note:318 This function does not validate the email. Call ``validate_email``319 first if you need to ensure the input is well-formed.320321 Args:322 email: A well-formed email address string.323324 Returns:325 The normalized email address in lowercase with plus-addressing removed.326327 Raises:328 ValueError: If the email does not contain an ``@`` symbol.329330 Examples:331 >>> normalize_email("Alice+tag@Example.COM")332 'alice@example.com'333 >>> normalize_email("BOB@COMPANY.ORG")334 'bob@company.org'335 """336 if '@' not in email:337 raise ValueError(f"Invalid email address (missing @): {email!r}")338 local, domain = email.rsplit('@', 1)339 local = local.split('+')[0]340 return f"{local.lower()}@{domain.lower()}"341342343class EmailValidator:344 """Validates email addresses with optional domain allowlisting.345346 Combines format validation with domain restriction. Useful for347 ensuring that only users with addresses from specific domains348 (e.g., corporate email) can register.349350 Attributes:351 allowed_domains: A set of lowercase domain strings that are352 permitted. Empty set means all domains are allowed.353354 Example:355 >>> validator = EmailValidator(allowed_domains=["company.com", "company.org"])356 >>> validator.is_valid("alice@company.com")357 True358 >>> validator.is_valid("bob@gmail.com")359 False360 >>> open_validator = EmailValidator()361 >>> open_validator.is_valid("anyone@anywhere.io")362 True363 """364365 def __init__(self, allowed_domains: Optional[list[str]] = None) -> None:366 """Initialize the validator with an optional domain allowlist.367368 Args:369 allowed_domains: A list of permitted email domains (case-insensitive).370 If None or empty, all domains are allowed.371 """372 self.allowed_domains = {d.lower() for d in (allowed_domains or [])}373374 def is_valid(self, email: str) -> bool:375 """Check whether an email address is valid and from an allowed domain.376377 Args:378 email: The email address to validate.379380 Returns:381 True if the email passes format validation and (if configured)382 its domain is in the allowlist. False otherwise.383 """384 if not validate_email(email):385 return False386 if self.allowed_domains:387 domain = email.rsplit('@', 1)[1].lower()388 return domain in self.allowed_domains389 return True390```391392**JSDoc equivalent (TypeScript):**393```typescript394/**395 * Validates whether a string is a well-formed email address.396 *397 * @param email - The email address string to validate.398 * @param strict - If true, applies stricter character rules in the local part.399 * @returns `true` if the email matches the expected pattern; `false` otherwise.400 *401 * @example402 * ```ts403 * validateEmail("alice@example.com"); // true404 * validateEmail("not-an-email"); // false405 * validateEmail("alice!@example.com", true); // false (strict mode)406 * ```407 */408export function validateEmail(email: string, strict = false): boolean {409 const pattern = strict410 ? /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/i411 : /^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$/i;412 return pattern.test(email);413}414```415416**GoDoc equivalent:**417```go418// Package email provides utilities for validating and normalizing email addresses.419//420// Example usage:421//422// if email.IsValid("alice@example.com") {423// canonical := email.Normalize("Alice+tag@Example.COM")424// fmt.Println(canonical) // alice@example.com425// }426package email427428// IsValid reports whether s is a well-formed email address.429// It uses a regex-based heuristic and is suitable for most real-world430// validation purposes. For strict RFC 5321 compliance, use IsValidStrict.431func IsValid(s string) bool { ... }432433// Normalize returns the canonical form of the email address by lowercasing434// both the local part and domain, and stripping any plus-addressing suffix435// (e.g., "Alice+tag@Example.COM" → "alice@example.com").436//437// Normalize does not validate the email. Call IsValid first if needed.438func Normalize(s string) (string, error) { ... }439```440441## Best Practices442- Write docs before or alongside code, not as an afterthought443- Keep docs close to the code they describe — co-located docstrings beat separate wiki pages444- Treat documentation as code: review it in PRs, update it with behavior changes445- Use examples liberally — a usage example is worth more than three paragraphs of prose446- Make the first sentence of a docstring a complete, standalone description (it appears in IDE tooltips and auto-generated indexes)447448## Common Mistakes449- Restating what the code does ("This function increments x by 1") instead of explaining purpose and contract450- Documenting parameters without types or units (is `timeout` in ms or seconds?)451- Outdated docs that contradict the current behavior — worse than no docs452- Missing exception documentation — callers can't handle errors they don't know about453- Documenting private/internal implementation details that may change vs. the stable public API454455## Tips & Tricks456- `pydoc`, `sphinx`, `typedoc`, and `godoc` generate HTML API references from docstrings automatically457- Keep a Changelog (keepachangelog.com) is the standard CHANGELOG format — follow it consistently458- Use `# TODO(username): reason` format for deferred work so it's trackable459- Add examples to docstrings that are also run as doctests in Python: `pytest --doctest-modules`460- Badge generators: shields.io creates badges for README (CI status, version, license, coverage)461462## Related Skills463- [api-designer](../api-designer/SKILL.md)464- [code-reviewer](../code-reviewer/SKILL.md)465- [refactorer](../refactorer/SKILL.md)466- [test-writer](../test-writer/SKILL.md)