How to Store a Function in a List or Dictionary So That When the Index (Or Key) Is Called It Fires Off the Stored Function

Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?

Functions are first class objects in Python and so you can dispatch using a dictionary. For example, if foo and bar are functions, and dispatcher is a dictionary like so.

dispatcher = {'foo': foo, 'bar': bar}

Note that the values are foo and bar which are the function objects, and NOT foo() and bar().

To call foo, you can just do dispatcher['foo']()

EDIT: If you want to run multiple functions stored in a list, you can possibly do something like this.

dispatcher = {'foobar': [foo, bar], 'bazcat': [baz, cat]}

def fire_all(func_list):
for f in func_list:
f()

fire_all(dispatcher['foobar'])

Executing objects using dictionaries in Python

Currently the methods will be evaluated when the dictionary is declared. You could instead store the options as tuples of function reference and parameter value:

from foobar import mcc1, mcc2

dict = {"task_a": ((mcc1.something_useful, '42')),
(mcc1.something_useful_too, '42')),

"task_b": ((mcc2.something_useful, '42'),
(mcc2.something_useful_too, '42'))}

def handler(foo, bar):

for key in dict.keys():

try:

dict[key][0](dict[key][1])

except error1 as er:

dict[key][1](dict[key[1])

handler(foo, bar)

How to call a function using dictionary key Value?

Do not put () while you are using the function name as a value for the dictionary because as soon as python find () it will execute the function.
Instead just add the function name a = {'+': hello}

And then use the () while fetching the value from the dictionary

a["+"]()

Why is the function inside the dictionary executing before they're called

To store a function inside dictionary , you need to store the function name without the bracelet.

So in your case it should be like this :

selection_dict = {1: addName, 2:searchName} 

You should have looked more information on google on how to store a function inside a dict. This link will be an useful example for you : Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?

Defining functions in a Dictionary

Try {"a" : print("a"), "b" : print("b")}. As you can see it still prints a and b, even if you do not call it. This is due to the items being evaluated.

Instead of putting the results of the functions into the dict (the results are all None, as you do not return anything from your functions) you could put the functions themselves:

def add(a,b):
print(f'Sum of {a} and {b} is:',(a+b))
def diff(a,b):
print(f'Difference of {a} and {b} is:',(a-b))
def prod(a,b):
print(f'Product of {a} and {b} is:',(a*b))
n1 = 5
n2 = 3
op = int(input("Enter the command for operation (1-3): "))
dic = {1: add, 2: diff, 3: prod}
dic[op](n1, n2)

This code takes the function at the specified index and calls it with n1 and n2 as arguments.



Related Topics



Leave a reply



Submit