Python 3.8+typingterm
typing.SupportsIndex
Supports* protocols
A runtime-checkable protocol for objects usable as an index (has __index__).
Syntax
isinstance(obj, typing.SupportsIndex)
__index__ marks a 'genuine integer' as opposed to a float: it is what slices, range(), hex()/bin()/oct() and operator.index() demand. So float lacks it — isinstance(2.0, SupportsIndex) is False, while int and bool pass. The protocol itself arrived in Python 3.8.
Examples
from typing import SupportsIndex
print(isinstance(5, SupportsIndex)) # → True
print(isinstance(2.5, SupportsIndex)) # → False
print(isinstance(True, SupportsIndex)) # → True
from typing import SupportsIndex
class Idx: __index__ = lambda self: 1
print(isinstance(Idx(), SupportsIndex)) # → True
print('abc'[Idx()]) # → b
See also
Open in the full glossarydocs.python.orgReport an inaccuracy