I am trying to use the Python @property decorator on a dict in a class. The idea is that I want a specific value (call it "message") to be cleared after it is accessed. But I also want a different value (name it "last_message") to contain the last message set, and keep it until another message is set. In my opinion, this code will work:
>>> class A(object): ... def __init__(self): ... self._b = {"message": "", ... "last_message": ""} ... @property ... def b(self): ... b = self._b ... self._b["message"] = "" ... return b ... @b.setter ... def b(self, value): ... self._b = value ... self._b["last_message"] = value["message"] ... >>>
However, this is not like:
>>> a = A() >>> ab["message"] = "hello" >>> ab["message"] '' >>> ab["last_message"] '' >>>
I'm not sure what I did wrong? It seems to me that @property does not work, as I would expect it on dicts, but maybe I'm doing something else fundamentally wrong?
In addition, I know that I can simply use individual values ββin the class. But this is implemented as a session in a web application, and I need it to be a dict. I could either do this work, or make an entire session object to pretend it's a dict, or use separate variables, and hack it into working the rest of the code base. I would rather just make it work.
python dictionary properties setter getter
Carson myers
source share