'How would I call a function by using a dictionary?
I recently found some code that calls a function from a different directory like this:
modules["module_name"].function(parameters)
Then I had a thought about calling a function (but not a module; I already know how to do that) through lists in that format like so:
[function_name](parameters)
Solution 1:[1]
You can't call a function like that in a list. I don't know what that syntax you have there. t's not possible, but you can call method references from dicts or variables below
If you're function is stored in a dictionary like so
def add(x, y):
return x + y
some_dict = {
'add' : add
}
Then you can call it like so
some_dict['add'](10, 10)
Solution 2:[2]
Calling a function using list... you can have a list of functions and call it out from index
def foo(arg):
print(arg)
list_of_functions = [foo]
list_of_functions[0](3)
This also works with dictionaries, since functions are just pointers, as anything else.
But i believe you wanted to find the function by the name from variable, in that case, probably (idk, never went this route) use globals for that one
def foo(arg):
print(arg)
function_name = 'foo'
globals()[function_name](3)
P.S. I still wonder about 2.7 though
Solution 3:[3]
If the list is created in other module :
module.py it should looks like this:
def add(a,b):
return a+b
lista = [add]
And you could call the fuction like this in your own module:
from module import lista
res = lista[0](2,3)
print(res)
The important here is note that the function should be define before to list it and in the same module where the list is created. In other way your code will be broken.
Don't ask why but I have python 2.7 too
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 | smerkd |
| Solution 2 | Adam Bright |
| Solution 3 | user6610216 |
