Call the dict __getitem__ intercept method when passing it to the update method of another dict

As you know, python allows you to simply override the dict.__getitem__ method so that we can do something else in it when someone tries to extract some value from it.

I want to make code when one instance of the MyDict(dict) class is passed to the update method of another python dict instance. See below:

 class MyDict(dict): def __getitem__(self, item): print "Doing some stuff here" return dict.__getitem__(self, item) d1 = MyDict({'1': 1, '2': 2}) d2 = {} # I want to have d1.__getitem__ called, but it does not work :-( d2.update(d1) 
+4
source share
2 answers

All you need to do is subclass MyDict from object and create a .keys() method for it. See below:

 class MyDict(object): def __init__(self, items=()): self._dict = dict(items) def keys(self): return self._dict.keys() def __getitem__(self, item): print "Doing some stuff for item:", item return self._dict[item] def __setitem__(self, item, value): self._dict[item] = value # You can add some more dict methods d1 = MyDict({'1': 1, '2': 2}) d2 = {} # Now you will see some stuff executed for each # value extracted from d1 while updating d2 d2.update(d1) 
0
source

Try using collections.Mapping abstract base class (or collections.MutableMapping if it is reading and writing).

 import collections class MyDict(collections.Mapping): def __init__(self, *args, **kwargs): self.data = dict(*args, **kwargs) def __len__(self): return len(self.data) def __iter__(self): return iter(self.data) def __contains__(self, key): return key in self.data def __getitem__(self, key): print 'Doing some stuff here' return self.data[key] 
+1
source

Source: https://habr.com/ru/post/1436526/


All Articles