| name | type-safety-enforcer |
| description | Enforce type safety requirements by running mypy type checker, detecting missing type hints, verifying docstring presence on public APIs, and identifying type annotation gaps. Use when validating type coverage, ensuring type safety compliance, checking documentation completeness, or preparing code for strict type checking. |
Type Safety Enforcer
Enforces strict type safety requirements and documentation standards for the Maou project.
Core Requirements
Type hints: Required for ALL functions, methods, and class attributes
Docstrings: Required for ALL public APIs
Line length: 88 characters maximum
No exceptions: Type safety is non-negotiable
Type Checking with mypy
Full Type Check
Run mypy on entire codebase:
uv run mypy src/
Per-Module Type Check
Check specific modules:
uv run mypy src/maou/domain/
uv run mypy src/maou/app/learning/
uv run mypy src/maou/infra/console/
Strict Mode Configuration
The project uses strict mypy configuration (see pyproject.toml):
[tool.mypy]
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
disallow_any_generics = true
Detecting Missing Type Hints
Find Functions Without Return Type Annotations
grep -rn "def [a-z_]" src/maou/ | grep -v " ->" | grep -v "__" | grep -v "test_" | head -20
Find Methods Without Parameter Type Hints
grep -rn "def .*(.*[a-z_][a-z_]*[,)]" src/maou/domain/ | grep -v ": " | head -20
Check Class Attributes
grep -rn "^ [a-z_].*= " src/maou/domain/ | grep -v ": " | head -20
Verifying Docstrings
Check Public Functions Have Docstrings
grep -A3 "^def [a-z]" src/maou/domain/ | grep -B3 "def " | grep -v '"""' | grep "def "
Check Public Classes Have Docstrings
grep -A3 "^class [A-Z]" src/maou/domain/ | grep -B3 "class " | grep -v '"""' | grep "class "
Docstring Format Validation
Docstrings should follow this format:
def convert_hcpe(input_path: Path, output_path: Path) -> int:
"""
将棋の棋譜データを処理し,HCPE形式に変換する.
Args:
input_path: 入力ファイルのパス
output_path: 出力ファイルのパス
Returns:
変換されたレコードの数
Raises:
ValueError: 入力形式が不正な場合
"""
Note: Japanese docstrings use 全角コンマ(,)and 全角ピリオド(.)
Common Type Hint Patterns
Function Type Hints
def calculate_loss(
policy_output: torch.Tensor,
value_output: torch.Tensor,
targets: torch.Tensor
) -> tuple[torch.Tensor, dict[str, float]]:
"""Calculate policy and value loss."""
...
def calculate_loss(policy_output, value_output, targets):
...
Class Attribute Type Hints
class TrainingConfig:
"""Training configuration."""
batch_size: int
learning_rate: float
epochs: int
device: str
def __init__(self, batch_size: int = 256) -> None:
self.batch_size = batch_size
Optional and Union Types
from typing import Optional, Union
def load_model(path: Path, device: Optional[str] = None) -> torch.nn.Module:
"""Load model from path."""
...
def process_input(data: Union[Path, str, list[Path]]) -> list[Path]:
"""Process various input formats."""
...
Generic Types
from typing import TypeVar, Generic
T = TypeVar('T')
class DataSource(Generic[T]):
"""Generic data source."""
def load(self) -> list[T]:
"""Load data items."""
...
Type Checking Error Resolution
Common mypy Errors
1. Missing return type
def process() -> None:
...
2. Untyped function definition
def convert(input: Path, output: Path) -> int:
...
3. Incompatible return value
def count() -> int:
return 0
4. Need type annotation
data: list[str] = []
Integration with QA Pipeline
Type checking is part of the QA pipeline:
uv run ruff format src/
uv run ruff check src/ --fix
uv run isort src/
uv run mypy src/
uv run pytest
Continuous Type Safety
Pre-commit Hook
Type checking runs automatically on commit:
uv run bash scripts/pre-commit.sh
CI/CD Integration
GitHub Actions run mypy on every push and PR.
Local validation prevents CI failures:
uv run mypy src/
Type Stub Files
For third-party libraries without type stubs:
uv add --dev types-requests
uv add --dev types-PyYAML
Project already has stubs for:
- numpy (via numpy)
- torch (via torch)
- click (via click)
Success Criteria
Type safety enforcement passes when:
- ✓
uv run mypy src/ exits with 0 errors
- ✓ All public functions have type hints
- ✓ All public APIs have docstrings
- ✓ No
# type: ignore comments (except for justified cases)
- ✓ Generic types properly parameterized
When to Use
- Before committing code
- After adding new functions or classes
- When refactoring
- During code review
- Before pull requests
- After dependency updates
- When fixing type errors
References
- CLAUDE.md: Type safety requirements (line 10, lines 49-50)
- AGENTS.md: Type hints required everywhere (line 14)
pyproject.toml: mypy strict configuration
- Python typing documentation: https://docs.python.org/3/library/typing.html