Python Callableの型ヒントの書き方|collections.abcとtypingの違い・callableとのエラー・ParamSpec
Pythonで「関数を受け取る引数」に型ヒントを付けるときは、from collections.abc import CallableとしてCallable[[引数の型, ...], 戻り値の型]と書きます。typing.Callableも動きますが、Python 3.9以降は非推奨の別名なので、新しく書くコードではcollections.abcから読み込みます。
この記事では、書き方の早見表、小文字のcallableと取り違えたときのエラー、mypyで実際に弾かれる例、デコレータ(ParamSpec)やキーワード引数が必要なときのProtocolまで、Python 3.12とmypy 2.4.0で動かした結果つきで説明します(2026年10月18日確認)。
Callableの型ヒントの書き方(早見表)
角括弧の中は必ず「引数の型のリスト」と「戻り値の型」の2つです。引数の部分はさらに角括弧で囲みます。
| 書き方 | 意味 | 当てはまる関数の例 |
|---|---|---|
Callable[[int], str] |
intを1つ受け取り、strを返す | def f(n: int) -> str |
Callable[[int, int], int] |
intを2つ受け取り、intを返す | def add(x: int, y: int) -> int |
Callable[[], None] |
引数なし、戻り値なし | def on_close() -> None |
Callable[..., int] |
引数は何でもよく、intを返す | len、intなど |
Callable[[str], Awaitable[None]] |
strを受け取るasync関数 | async def f(s: str) -> None |
Callable[P, R] |
引数の形をそのまま引き継ぐ(ParamSpec) | 汎用デコレータ |
基本の例です。
from collections.abc import Callable
def apply(fn: Callable[[int, int], int], a: int, b: int) -> int:
return fn(a, b)
def add(x: int, y: int) -> int:
return x + y
print(apply(add, 2, 3))
print(apply(lambda x, y: x * y, 2, 3))
実行結果:
5
6
関数addは括弧を付けずに渡します。apply(add(2, 3), 2, 3)と書くと、先に実行された結果の5(int)が渡ってしまいます。
collections.abc.Callableとtyping.Callableの違い
中身は同じものです。Python公式ドキュメントでは、typing.Callableは「collections.abc.Callableの非推奨の別名」と書かれており、3.9でcollections.abc.Callableが[]による添字に対応したことが理由です(typing — Python 3.15.0 documentation、2026年10月18日確認)。
| 項目 | collections.abc.Callable |
typing.Callable |
|---|---|---|
| 使えるバージョン | 型ヒントの添字は3.9以降 | 3.5以降 |
| 位置づけ | 推奨 | 非推奨の別名(3.9から) |
| importしたときの警告 | なし | 現時点ではなし(そのまま動く) |
ParamSpec・Concatenate |
3.10以降で使える | 3.10以降で使える |
「非推奨」といっても、実行時にDeprecationWarningが出るわけではありません。警告をエラーにする設定(warnings.simplefilter("error"))でfrom typing import Callableを実行しても、何も起きないことを確認しました。既存のコードを急いで書き換える必要はありませんが、3.8以前をサポートしないならcollections.abcに揃えるのが今の書き方です。
リンターのRuffには、対象のPythonバージョンで非推奨になったimportを指摘するルール(UP035 deprecated-import)があります(Ruff公式ドキュメント、2026年10月18日確認)。チームで書き方を揃えたいときはリンターに任せると楽です。
「from collections.abc import callable」はエラーになる
検索でよく見かけるのがこの書き方です。大文字のCallableが型、小文字のcallableは組み込み関数で、別物です。
from collections.abc import callable
実行結果:
ImportError: cannot import name 'callable' from 'collections.abc' (...). Did you mean: 'Callable'?
小文字のcallable()はimport不要の組み込み関数で、「その値が()で呼び出せるか」をTrue/Falseで返します。実行時に調べたいならcallable()、型ヒントに書くならCallableと覚えてください。
from collections.abc import Callable
print(callable(len), callable("abc"))
print(isinstance(len, Callable), isinstance("abc", Callable))
class Adder:
def __call__(self, a: int, b: int) -> int:
return a + b
print(callable(Adder()), isinstance(Adder(), Callable))
実行結果:
True False
True False
True True
isinstance(x, Callable)でも判定できますが、引数の型までは調べません。isinstance(x, Callable[[int], str])のように添字付きで書くとTypeErrorになります。また__call__を持つクラスのインスタンスも「呼び出せるもの」として扱われます。
形が合わない関数はmypyが実行前に弾く
Callableを書く一番の利点は、渡した関数の形の間違いを、呼ばれる前に見つけられることです。次のファイルをmypyで検査します。
# c2.py
from collections.abc import Callable
def apply(fn: Callable[[int, int], int], a: int, b: int) -> int:
return fn(a, b)
def add(x: int, y: int) -> int:
return x + y
def shout(s: str) -> str:
return s.upper()
apply(add, 2, 3)
apply(shout, 2, 3)
apply(len, 2, 3)
apply(add(2, 3), 2, 3)
$ mypy c2.py
c2.py:13: error: Argument 1 to "apply" has incompatible type "Callable[[str], str]"; expected "Callable[[int, int], int]" [arg-type]
c2.py:14: error: Argument 1 to "apply" has incompatible type "Callable[[Sized], int]"; expected "Callable[[int, int], int]" [arg-type]
c2.py:15: error: Argument 1 to "apply" has incompatible type "int"; expected "Callable[[int, int], int]" [arg-type]
Found 3 errors in 1 file (checked 1 source file)
引数の型が違う関数、引数の数が違うlen、そして括弧を付けて結果を渡してしまったミス(15行目)の3つが見つかりました。コールバックは「登録した時点」と「実際に呼ばれる時点」が離れているため、実行してからTypeErrorで気づくより、型チェックで先に見つけるほうがはるかに楽です。
よくあるエラー:Callable[int, str]と書いてしまう
引数の部分を角括弧で囲み忘れると、typing.Callableでは実行時にエラーになります。
from typing import Callable
Callable[int, str]
TypeError: Expected a list of types, an ellipsis, ParamSpec, or Concatenate. Got <class 'int'>
一方、collections.abc.Callable[int, str]は実行時にはエラーにならず、そのまま通ってしまいました(Python 3.12で確認)。mypyでは次のように指摘されます。
error: The first argument to Callable must be a list of types, parameter specification, or "..." [valid-type]
実行して気づけない場合があるので、Callableを書いたら型チェッカーを一度通す習慣をつけると安全です。
引数を問わないときは「…」
from collections.abc import Callable
handlers: dict[str, Callable[..., None]] = {}
def register(name: str, fn: Callable[..., None]) -> None:
handlers[name] = fn
def on_click(x: int, y: int) -> None: ...
def on_close() -> None: ...
register("click", on_click)
register("close", on_close)
print(list(handlers))
実行結果:
['click', 'close']
...は「引数はどんな形でもよい」という意味で、引数の数が違う関数をまとめて登録したいときに使います。そのかわり、呼び出すときの引数の検査も効かなくなります。形を揃えられるなら具体的に書くほうが安全です。
デコレータの型ヒントはParamSpecで書く
デコレータは「関数を受け取って関数を返す」ので、引数も戻り値もCallableです。ただしCallable[[int], int]のように固定すると、その形の関数にしか付けられません。どんな関数にも付けられるデコレータはParamSpec(3.10以降)で書きます。Python 3.12以降なら、次のように型パラメータの構文([**P, R])が使えます。
from collections.abc import Callable
import functools
def log[**P, R](fn: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(f"呼び出し: {fn.__name__}{args}")
return fn(*args, **kwargs)
return wrapper
@log
def greet(name: str, times: int = 1) -> str:
return "こんにちは、" + name + "さん" * times
print(greet("佐藤"))
実行結果:
呼び出し: greet('佐藤',)
こんにちは、佐藤さん
mypyでreveal_type(greet)を調べるとdef (name: str, times: int =) -> strと表示され、デコレータを通しても元の引数の型が保たれていることが分かります。3.10〜3.11ではP = ParamSpec("P")、R = TypeVar("R")をtypingから読み込んで同じことを書きます。デコレータそのものの書き方は「Pythonデコレータ完全攻略 – 基本から実践応用まで徹底解説」、functools.wrapsは「Python functools.wraps()とは?デコレータで関数情報を保つ方法」で説明しています。
キーワード引数や可変長引数はProtocolで書く
Callableではキーワード専用引数・可変長引数・オーバーロードを表せません。公式ドキュメントでも、その場合は__call__を持つProtocolクラスを定義する方法が案内されています。
from typing import Protocol
class Handler(Protocol):
def __call__(self, path: str, *, verbose: bool = False) -> int: ...
def run(h: Handler) -> int:
return h("/data", verbose=True)
def good(path: str, *, verbose: bool = False) -> int:
return len(path)
def bad(path: str) -> int:
return len(path)
print(run(good))
run(bad)
実行すると5が表示されたあと、badの呼び出しでTypeError: bad() got an unexpected keyword argument 'verbose'になります。mypyなら実行前に指摘されます。
error: Argument 1 to "run" has incompatible type "Callable[[str], int]"; expected "Handler" [arg-type]
よくある質問
Q. typing.Callableはもう使えないのですか?
使えます。Python 3.9から非推奨の別名という扱いですが、importしても警告は出ず、そのまま動きます。新しく書くコードではfrom collections.abc import Callableを使うのがおすすめです。
Q. from collections.abc import callableでImportErrorになります
型の名前は大文字始まりのCallableです。小文字のcallableは組み込み関数なのでimportは不要で、callable(x)のようにそのまま使えます。
Q. 戻り値がない関数はどう書きますか?
戻り値の型にNoneを書きます。引数なし・戻り値なしならCallable[[], None]です。
Q. キーワード引数を持つ関数を型ヒントで表せますか?
Callableでは表せません。__call__メソッドを持つProtocolクラスを定義し、それを引数の型に使います。
Q. async関数を受け取る引数はどう書きますか?
async関数は呼び出すと待機可能なオブジェクトを返すので、Callable[[str], Awaitable[None]]のように戻り値をAwaitableで書きます。Awaitableもcollections.abcから読み込めます。
まとめ
- 書き方は
Callable[[引数の型, ...], 戻り値の型]。引数の部分は必ず角括弧で囲む - importは
from collections.abc import Callable。typing.Callableは3.9以降は非推奨の別名(動作はする) - 小文字の
callableは組み込み関数で、importできない - mypyに通すと、形の違う関数や括弧の付け忘れ・付けすぎを実行前に見つけられる
- 引数を問わないなら
Callable[..., R]、汎用デコレータはParamSpec、キーワード引数はProtocol
型ヒント全体の書き方は「Python typingモジュールとは?型ヒントの書き方を初心者向けに解説」、list[int]などのコレクションは「Python list[int]・dict[str, int]とは?コレクションの型ヒントの書き方」にまとめています。





