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)
(I use python 2.7 don't ask why)
CodePudding user response:
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)
CodePudding user response:
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