I want a method get called when a member variable, which is a dictionary, is edited(in any way).
Is there any way I can achieve this without declaring a new class?
For example,
class MyClass:
def __init__(self):
self.dictionary = {}
def __setattr__(self, key, value):
super().__setattr__(key, value)
# DO SOMETHING
This will ONLY work when I use
self.dictionary = {}
, not working when
self.dictionary[some_key] = some_value
And @property
- @dictionary.setter
will result the same.
Yes, I know it'll call __setitem__
of that dict, so making a new class such as
class MyDict(dict):
# override __setitem__ and other methods called when modifying the values
will work.
But the thing is,
I need to use for list as well, and there are lots of methods that modifies the value.
I need to use
Dict[int, List[int]]
like this, and it'll be very messy.I need to dump that data with pickle, so I'll need to define
__getstate__
and__setstate__
to avoid weakref error if I make a new class.
+For clearance, what I ultimately want is a method of MyClass
that is called when all of the some_func
's cases.
class MyClass:
def __init__(self):
self.data: Dict[int, List[int]] = {}
def some_func(self):
self.data[1].append(10)
self.data.popitem()
self.data[2] = []
# And any other things that changes the data...
I would appreciate any idea, thank you.