'Calling a function in the dictionary in parallel with obtaining a value
I want to pass a key to a dictonary, get an attached to this key value and also call a function attached to same key if the function is present. I'm able to create something like this d={'some_key':('value', func())}, but it calls the function when the dictonary is initialized. I know that I can get a tuple with value and fucntion, check the length of this tuple and if the length equals 2 then call a function, but isn't there a more elegant way? Can I somehow make the functon activate only when I input a certain key without any other syntax? Just write d[some_key], get a corresponding value and execute a function without any additional brackets.
Solution 1:[1]
You'd need to subclass dict to override the __getitem__ method:
class MyDict(dict):
def __getitem__(self, index):
a, b = super().__getitem__(index)
return a, b()
def myfunc():
return "Hello world"
mydict = MyDict({'a': (100, myfunc)})
print(mydict['a'])
outputs
(100, 'Hello world')
If you want to call the function and return the value:
class MyDict(dict):
def __getitem__(self, index):
a, b = super().__getitem__(index)
b()
return a
Note that this is very unexpected behavior, so make sure your users know what will happen when they use this dictionary.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rassar |
