Back to skills
SKILL.md
Type Annotation
ASecurityWrite type annotations in Python even for small or throwaway-looking scripts. Annotate function parameters and return values, class attributes, and module-level constants, and spell out the element types of generic containers such as dict and tuple. Use when writing or reviewing Python code.
- 3 stars
- 0 votes
- 0 copies
- 0 views
- Added December 3, 2026
Security analysis
100/100npx -y skills add ncaq/konoka --skill type-annotation --agent claude-codeAre you the author of Type Annotation?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/ncaq-type-annotation)---
name: type-annotation
description: Write type annotations in Python even for small or throwaway-looking scripts. Annotate function parameters and return values, class attributes, and module-level constants, and spell out the element types of generic containers such as dict and tuple. Use when writing or reviewing Python code.
user-invocable: false
---
# 小さなスクリプトでも型注釈を書く
Pythonのコードには、
小さなものや使い捨てに見えるものでも、
なるべく型注釈を書いてください。
数十行のスクリプトや、
他のモジュールの内容を集めるだけの`__init__.py`も対象です。
Pythonの型注釈は省略できますが、
省略した部分は型検査器が型を知ることができず、
誤りがあっても実行するまで見つかりません。
pyrightは既定値の無い引数に型注釈が無いと、
その引数を型の分からない値として扱います。
mypyは既定では型注釈の無い関数の中身を検査しません。
型注釈は、
何を受け取って何を返すのかを、
中身を読まなくても分かるようにする説明にもなります。
その説明が実装と食い違っていないことは型検査器が確かめます。
小さなスクリプトも、
後から機能を足されたり他のコードから読み込まれたりします。
小さいうちに書いておけば手間はわずかで、
後から型検査の対象に入れる時に書き直さずに済みます。
## 型注釈を書く場所
- 関数の引数と戻り値。
何も返さない関数にも`-> None`を書きます。
戻り値の型は推論もされますが、
書いておけば中身を変えた時に意図せず型が変わったことに気付けます。
- クラスの属性。
インスタンスの属性はクラスの本体で型と一緒に宣言します。
インスタンスごとではなくクラスで共有する値には`ClassVar`を付けます。
- モジュールのトップレベルの定数。
再代入しない値には`Final`を付けます。
文字列や数値のリテラルのように値から型が明らかなものは、
`Final`とだけ書けば型は値から決まります。
局所変数は型注釈を書かずに推論に任せて構いません。
ただし空の`list`や`dict`のように、
値から要素の型が決まらない時は書きます。
## ジェネリクスは要素の型まで書く
`dict`や`list`や`tuple`などのコンテナの型は、
`dict[str, int]`のように要素の型まで書きます。
`dict`とだけ書くと要素の型が分からないままになり、
取り出した値に対する操作が型検査されなくなります。
pyrightのstrictモードでは、要素の型を省いた`dict`はエラーになります。
- `tuple`は、
要素の数が決まっているなら`tuple[int, str]`、
決まっていないなら`tuple[int, ...]`と書きます。
- `typing.Dict`や`typing.List`ではなく、組み込みの`dict`や`list`を使います。
`typing`の方は非推奨の別名です。
- `Optional[X]`や`Union[X, Y]`ではなく、`X | None`や`X | Y`と書きます。
コンテナの定数は、
値から推論させずに`Final[dict[str, int]]`のように型を書きます。
推論される型はその時点で入っている値から決まるので、
意図した型とは限らないためです。
```python
import sys
from pathlib import Path
from typing import Final
# コンテナの定数は要素の型まで書く
IMAGE_SUFFIXES: Final[frozenset[str]] = frozenset({".jpg", ".png", ".webp"})
# リテラルの定数は値から型が決まるので`Final`だけで良い
MAX_DEPTH: Final = 3
class ImageScanner:
# インスタンスの属性はクラスの本体で宣言する
root: Path
skipped: int
def __init__(self, root: Path) -> None:
self.root = root
self.skipped = 0
def scan(self) -> dict[str, list[Path]]:
# 空の`dict`は値から要素の型が決まらないので書く
groups: dict[str, list[Path]] = {}
for path in self.root.rglob("*"):
if MAX_DEPTH < len(path.relative_to(self.root).parts):
self.skipped += 1
elif path.suffix in IMAGE_SUFFIXES:
groups.setdefault(path.suffix, []).append(path)
return groups
def main(argv: list[str]) -> None:
scanner = ImageScanner(Path(argv[1]))
for suffix, paths in sorted(scanner.scan().items()):
print(f"{suffix}: {len(paths)}")
print(f"skipped: {scanner.skipped}")
if __name__ == "__main__":
main(sys.argv)
```
## 型の定義を増やすことまでは求めない
このルールが求めるのは、
関数やクラスや定数に、
その型を注釈として書くことです。
型検査のエラーを避けるためだけに、
型エイリアスなどの型の定義を新しく増やすことまでは求めません。
小さなスクリプトに型の定義が増えると、
読みやすくするための型注釈が、
かえってコードを読みにくくするためです。
Attribution
Related skills
View all in ai-agents →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.