Python 3.3+collectionsterm
collections.abc.Sized
collections.abc — protocols
The protocol for objects with a length (has __len__).
Syntax
isinstance(obj, collections.abc.Sized)
The check is structural: isinstance returns True for any class that defines __len__, with no inheritance or registration needed. Sized says nothing about iteration or indexing, and the reverse also holds — a generator is iterable but not Sized, so len() on it fails, and that is exactly the case Sized lets you screen out beforehand.
Examples
import collections.abc as abc
print(isinstance([1, 2], abc.Sized)) # → True
print(isinstance('hello', abc.Sized), isinstance({'a': 1}, abc.Sized)) # → True True
print(isinstance(42, abc.Sized)) # → False
print(isinstance((i for i in range(3)), abc.Sized)) # → False
print(issubclass(abc.Sequence, abc.Sized), issubclass(abc.Iterator, abc.Sized)) # → True False
See also
Open in the full glossarydocs.python.orgReport an inaccuracy