Skip to content
Advertisement

How does Python’s reversed() function work?

According to Python’s docs, reversed() uses __getitem__ and __len__ if __reversed__ is not implemented.

I’ve encountered a weird behavior and failed to explain it:

JavaScript

Although calling reversed() on mapping types makes no sense, how does it know it’s a mapping? Does it internally check isinstance(inst, dict)? Does it check for any general mapping like collections.abc.Mapping? Is there any way to override this behavior without implementing __reversed__?

I thought it might be due to dict implementing a __reversed__ that throws a TypeError, or one that equals None much like how you disable __hash__, but dict.__reversed__ turned out empty with AttributeError thrown.

UPDATE:

New Python versions implement __reversed__ for dictionaries. Mapping protocols (such as collections.abc.Mapping) set __reversed__ to None.

Advertisement

Answer

Yes, there’s a check for dict type in PySequence_Check used by reversed.

JavaScript
Advertisement