Python Glossary Русский

Python 3.8+typingfunction

typing.runtime_checkable

decorators and markers

A decorator letting a Protocol be used with isinstance()/issubclass() by method presence.

Syntax

@typing.runtime_checkable

The main trap: isinstance() against such a protocol checks only that the methods exist by name, not their signatures — an object whose __len__ takes the wrong arguments still passes. And issubclass() works only for method-only protocols; against a protocol with data attributes it raises TypeError.

Examples

from typing import Protocol, runtime_checkable
@runtime_checkable
class Sized(Protocol):
    def __len__(self) -> int: ...
print(isinstance([1, 2], Sized))   # → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy