2

I would like to inherit the OrderedDict class to set up a maximum length to the dict.

I did :

from collections import OrderedDict

class limitedDict(OrderedDict):
    def __init__(self, length):
        OrderedDict.__init__(self)
        self.length = length

But now I don't see which function to overwrite to catch the "adding a key" event. I Googled for a while without finding the answer. Even special functions are not clearly an answer.

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Romain Jouin
  • 4,448
  • 3
  • 49
  • 79

1 Answers1

1

Use the dunder method __setitem__ as mentioned in the comments by @AshwiniChaudhary. You need to distinguish overwriting and setting a new key, though.

from collections import OrderedDict

class limitedDict(OrderedDict):
    def __init__(self, length):
        OrderedDict.__init__(self)
        self.length = length

    def __setitem__(self, key, value):
        if key not in self and len(self) >= self.length:
            raise RuntimeWarning("Dictionary has reached maximum size.")
            # Or do whatever else you want to do in that case
        else:
            OrderedDict.__setitem__(self, key, value)

Note that while the update method also allows adding new keys, it calls __setitem__ under the hood, as mentioned in the comments.

If the dictionary exceeds the maximum size you might want to self.popitem(last=False) until it matches the length (last=False for FIFO order, last=True for LIFO order, the default).

Graipher
  • 6,891
  • 27
  • 47