Another possible solution, is to create a custom dictionary object that implements this behavior:
>>> class CallableDict(dict):
... def __getitem__(self, key):
... val = super().__getitem__(key)
... if callable(val):
... return val()
... return val
...
>>>
>>> d = CallableDict({1: "A", 2: "B", 3: lambda: print('run')})
>>> d[1]
'A'
>>> d[3]
run
A perhaps more idiomatic solution would be to use try/except
:
def __getitem__(self, key):
val = super().__getitem__(key)
try:
return val()
except TypeError:
return val
Note however the method above is really for completness. I would not reccomend using it. As pointed out in the comments, it would mask TypeError
's raised by the function. You could test the exact content of TypeError
, but at that point, you'd be better of using the LBYL style.