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 maximeLeurent
Recipients docs@python, maximeLeurent
Date 2021-07-30.16:22:34
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1627662154.37.0.411643198331.issue44782@roundup.psfhosted.org>
In-reply-to
Content
Hello,

I try to use a dictionnary with limited size, and I use class LRU given in docs on OrderedDict.

Unfortunately this class is, somehow, not working on pop method.

I say somehow because if I do OrderedDict pop method by hand I don't get any Exception. I do not understand how LRU.__getitem__ is call after del, and why "value = super().__getitem__(key)" work, when "self.move_to_end(key)" don't

Code tested on python3.7 and python3.8:


from collections import OrderedDict

class LRU(OrderedDict):
    'Limit size, evicting the least recently looked-up key when full'

    def __init__(self, maxsize=128, *args, **kwds):
        self.maxsize = maxsize
        super().__init__(*args, **kwds)

    def __getitem__(self, key):
        value = super().__getitem__(key)
        self.move_to_end(key) #<=== Bug here
        return value

    def __setitem__(self, key, value):
        if key in self:
            self.move_to_end(key)
        super().__setitem__(key, value)
        if len(self) > self.maxsize:
            oldest = next(iter(self))
            del self[oldest]


d = LRU()
d["foo"] = "bar"
d.pop("foo") #<= KeyError on mode_to_send in LRU.__getitem__ method

#pop method by "hand"  
d["foo2"] = "bar"
if "foo2" in d :
    result = d["foo2"]
    del d["foo2"]
    print(result) #work fine
History
Date User Action Args
2021-07-30 16:22:34maximeLeurentsetrecipients: + maximeLeurent, docs@python
2021-07-30 16:22:34maximeLeurentsetmessageid: <1627662154.37.0.411643198331.issue44782@roundup.psfhosted.org>
2021-07-30 16:22:34maximeLeurentlinkissue44782 messages
2021-07-30 16:22:34maximeLeurentcreate