Home > Enterprise >  dictionary that executes function when the key is accessed
dictionary that executes function when the key is accessed

Time:09-18

I am looking for a way to achieve the following: A dictionary that returns the current datetime when the key is accessed. (So NOT the datetime of when the key was stored)

Example that does not do what i want:

d = {'key': datetime.datetime.now()}
d['key'] # returns datetime of dic creation instead of current

As my dictionary key will be accessed by existing code outside of my control, i am unable to do things like d['key'](). I was hoping of something similar to the @property decorator for classes, which executes a function when accessed

CodePudding user response:

If you make your thing a subclass of dict you can intercept the __getitem__ method:

class MyDict(dict):
    def __getitem__(self, item):
        val = super().__getitem__(item)
        if callable(val):
            return val()
        else:
            return val

def func():
    return "ran function"

d = MyDict(a=1, f=func)

print(d["a"])
print(d["f"])

outputs:

1
ran function
  • Related