This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Dennis Sweeney
Recipients Dennis Sweeney, Thor Whalen2, docs@python, rhettinger, stutzbach
Date 2020-04-23.21:27:57
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1587677278.15.0.840790535156.issue40374@roundup.psfhosted.org>
In-reply-to
Content
> `Mapping.__reversed__` exists

While ``'__reversed__' in dir(Mapping)`` is true, that unfortunately does not mean that it is a real callable method:


    from collections.abc import Mapping
    class Map(Mapping):
        def __getitem__(self, x):
            if x == 42:
                return 17
            raise KeyError
        def __len__(self, x):
            return 1
        def __iter__(self):
            yield 42
		
    >>> m = Map()
    >>> reversed(m)
    Traceback (most recent call last):
    ...
    TypeError: 'Map' object is not reversible

In the code for Mapping, ``__reversed__`` is explicitly defined as None [1] so that calling ``reversed(custom_mapping)`` doesn't accidentally fall back on the sequence protocol, which would mean starting at len(custom_mapping)-1 and calling __getitem__ on each index [2], which is certainly not desirable for arbitrary mappings.

I don't think there is a reasonable way, given arbitrary implementations of __len__, __iter__, and __getitem__, to have a mixin reversed iterator.  If someone wants their mapping to have a __reversed__ method, they should define it themselves.

[1] https://github.com/python/cpython/blob/master/Lib/_collections_abc.py#L707
[2] https://docs.python.org/3/reference/datamodel.html?highlight=__reversed__#object.__reversed__
History
Date User Action Args
2020-04-23 21:27:58Dennis Sweeneysetrecipients: + Dennis Sweeney, rhettinger, stutzbach, docs@python, Thor Whalen2
2020-04-23 21:27:58Dennis Sweeneysetmessageid: <1587677278.15.0.840790535156.issue40374@roundup.psfhosted.org>
2020-04-23 21:27:58Dennis Sweeneylinkissue40374 messages
2020-04-23 21:27:57Dennis Sweeneycreate