Python Glossary Русский

Python 3.6+collectionsterm

collections.abc.Reversible

collections.abc — protocols

The protocol for objects supporting reversed() (has __reversed__).

Syntax

isinstance(obj, collections.abc.Reversible)

The check looks for __reversed__ (plus __iter__), but the reversed() builtin is happy with just __len__ and __getitem__ — so a plain sequence-protocol class reverses fine yet fails the isinstance test. Inherit from Sequence if you want the two to agree; Sequence is already declared Reversible. Generators and ordinary iterators are excluded, because a stream with no known end cannot be walked backwards.

Examples

import collections.abc as abc
print(isinstance([1], abc.Reversible))   # → True
print(isinstance(range(3), abc.Reversible))   # → True
print(isinstance({'a': 1, 'b': 2}, abc.Reversible))   # → True
print(list(reversed({'a': 1, 'b': 2})))   # → ['b', 'a']
print(isinstance({1, 2}, abc.Reversible))   # → False
print(isinstance((x for x in [1, 2]), abc.Reversible))   # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy