Below is a class MyDict
that inherits from dict
. What I want to
do is basically to perform some operation each time a key of a
MyDict
object is assigned a value. So __setitem__
is my friend
here:
JavaScript
x
9
1
class MyDict(dict):
2
def __setitem__(self, key, value):
3
print(f'key {key} set to {value}')
4
super().__setitem__(key, value)
5
6
m = MyDict()
7
m[0] = 'hello' # prints "0 set to hello"
8
m[1] = 'world!' # prints "1 set to world!"
9
This is great but now if I do this, __setitem__
is not called anymore.
JavaScript
1
2
1
m = MyDict({0: 'hello', 1: 'world!'})
2
I could of course overload __init__
to solve my problem but is
there a simpler solution?
Besides, as I understand the dict.__init__
help message:
JavaScript
1
5
1
| dict(iterable) -> new dictionary initialized as if via:
2
| d = {}
3
| for k, v in iterable:
4
| d[k] = v
5
__setitem__
should be called in my example. Have I misunderstood
something?
Advertisement
Answer
You should subclass UserDict
:
JavaScript
1
8
1
from collections import UserDict
2
3
class MyDict(UserDict):
4
def __setitem__(self, key, value):
5
print(f'key {key} set to {value}')
6
7
m = MyDict({0: 'hello', 1: 'world!'})
8
Outputs
JavaScript
1
3
1
key 0 set to hello
2
key 1 set to world!
3
Related questions: Subclass dict: UserDict, dict or ABC? and list vs UserList and dict vs UserDict