Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary value as function to be called when key is accessed, without using "()"

I have a dictionary that has values sometimes as strings, and sometimes as a functions. For the values that are functions is there a way to execute the function without explicitly typing () when the key is accessed?

Example:

d = {1: "A", 2: "B", 3: fn_1}
d[3]() # To run function

I want:

d = {1: "A", 2: "B", 3: magic(fn_1)}
d[3] # To run function
like image 879
tyleax Avatar asked Sep 08 '17 00:09

tyleax


People also ask

How can we get value from dictionary without key?

You just have to use dict. values() . This will return a list containing all the values of your dictionary, without having to specify any key.

Can the values of a dictionary can be accessed using keys?

Explanation: The values of a dictionary can be accessed using keys but the keys of a dictionary can't be accessed using values.

Can Python dictionary value be a function?

Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.

How are values in a dictionary accessed?

The well-known, or I should say the traditional way to access a value in a dictionary is by referring to its key name, inside a square bracket. Notice that when you want to access the value of the key that doesn't exist in the dictionary will result in a KeyError.


1 Answers

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.

like image 162
Christian Dean Avatar answered Oct 13 '22 22:10

Christian Dean