Python 3.3+collectionsterm
collections.abc.Sequence
collections.abc — protocols
The immutable sequence protocol (indexing, slicing, len, in).
Syntax
isinstance(obj, collections.abc.Sequence)
The classic trap: str is a Sequence, so this check will not separate a list of strings from a single string, and your function will happily iterate it character by character — screen strings out explicitly. Do not read it as "read-only" either: list is a Sequence too, because MutableSequence derives from it, and there is no ABC meaning "cannot be modified". For your own class only __getitem__ and __len__ are required; __contains__, __iter__, __reversed__, index and count arrive as mixins.
Examples
import collections.abc as abc
print(isinstance([1], abc.Sequence)) # → True
print(isinstance((1,), abc.Sequence)) # → True
print(isinstance('hello', abc.Sequence), isinstance(range(3), abc.Sequence)) # → True True
print(isinstance({1, 2}, abc.Sequence), isinstance({'a': 1}, abc.Sequence)) # → False False
print(isinstance(iter([1, 2]), abc.Sequence)) # → False
print(issubclass(list, abc.MutableSequence), issubclass(tuple, abc.MutableSequence)) # → True False
See also
Open in the full glossarydocs.python.orgReport an inaccuracy