Python Glossary Русский

Python 3.3+collectionsterm

collections.abc.Callable

collections.abc — protocols

The abstract base class for callable objects: used in isinstance checks and, above all, in annotations like Callable[[int], str].

Syntax

from collections.abc import Callable
def apply(f: Callable[[int], str], x: int) -> str: ...

For a runtime check the built-in callable(obj) is simpler: it looks at the type's call slot, while isinstance(obj, Callable) looks for __call__ in the MRO, and they disagree at the edges — a class with __call__ = None is callable() but not a Callable. The parameterised form Callable[[int], str] is for annotations only: isinstance with it raises TypeError, and nothing checks the signature at runtime. typing.Callable is a deprecated alias of this same class; since 3.9 write collections.abc.Callable.

Examples

from collections.abc import Callable
print(isinstance(len, Callable), isinstance(42, Callable))  # → True False
class Box:
    __call__ = None
print(callable(Box()), isinstance(Box(), Callable))  # → True False — края расходятся
# Python 3.9+
from collections.abc import Callable
def apply(f: Callable[[int], str], x: int) -> str:
    return f(x)
print(apply(hex, 255))  # → 0xff
try:
    isinstance(hex, Callable[[int], str])
except TypeError as e:
    print(e)  # → isinstance() argument 2 cannot be a parameterized generic

See also

Open in the full glossarydocs.python.orgReport an inaccuracy