[New-bugs-announce] [issue44782] LRU class given as example in OrderedDict example not work on pop

Maxime LEURENT report at bugs.python.org
Fri Jul 30 12:22:34 EDT 2021


New submission from Maxime LEURENT <maxime.leurent at gmx.fr>:

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

----------
assignee: docs at python
components: Documentation
messages: 398571
nosy: docs at python, maximeLeurent
priority: normal
severity: normal
status: open
title: LRU class given as example in OrderedDict example not work on pop
versions: Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44782>
_______________________________________


More information about the New-bugs-announce mailing list