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
Add Leading Zeros to Strings in Pandas Dataframe
Lost Connection to MySQL Server During Query
How to Include Third Party Python Libraries in Google App Engine
Transpose Column to Row with Spark
Editing the Date Formatting of X-Axis Tick Labels in Matplotlib
Typeerror: '<=' Not Supported Between Instances of 'Str' and 'Int'
Horizontal Stacked Bar Plot and Add Labels to Each Section
Python: Problem with Raw_Input Reading a Number
In Practice, What Are the Main Uses for the "Yield From" Syntax in Python 3.3
What's the How to Install Pip, Virtualenv, and Distribute for Python
What's the Difference Between Select_Related and Prefetch_Related in Django Orm
What's the Function Like Sum() But for Multiplication? Product()
Parallel Processing from a Command Queue on Linux (Bash, Python, Ruby... Whatever)
Negative Integer Division Surprising Result