Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a function call to a list?

I have a Python code that uses the following functions:

def func1(arguments a, b, c):

def func2(arguments d, e, f):

def func3(arguments g, h, i):

Each of the above functions configures a CLI command on a product.

In addition, for each of the above functions, there is the de-init function which deletes the CLI command.

def de_init_func1(arguments x, y, z):

def de_init_func2(arguments l, m, n):

def de_init_func3(arguments q, r, s):

Suppose I have a script which configures lots of CLI commands using the functions func1, func2 and func3, and before the script completes, the script should remove all the CLI commands that it configured.

For this to happen, each time func1/2/3 is invoked, I need to add the equivalent de_init_func CALL to a list, so by the end of the script, I can iterate this list, and invoke the de-init methods one by one.

How can I add a "func1(arguments) call" to a list without invoking it while adding it to the list.

If I will just add the func1(arguments) call as a string "func1(arguments)", once I will iterate the list, I won`t be able to invoke the function calls because interpreter will refer to the list items as strings and not as function calls...

like image 663
qwerty Avatar asked Nov 12 '14 07:11

qwerty


People also ask

Can you put function calls in a list Python?

At the simplest level, you can simply use tuples for referencing function calls. For example, a call to func1(a, b, c) would be referenced by the tuple (func1, a, b, c) . You can then safely put those tuples in a list. That is : call the function in t[0] with the arguments in the remaining of typle.

Can you call a function on a list?

Answer. Yes, the variable in the for of a list comprehension can be used as a parameter to a function.

How do you create a function call in Python?

In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon. The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.


1 Answers

At the simplest level, you can simply use tuples for referencing function calls. For example, a call to func1(a, b, c) would be referenced by the tuple (func1, a, b, c). You can then safely put those tuples in a list.

To execute later the function represented by such a tuple (say t), simply use :

t[0](*t[1:])

That is : call the function in t[0] with the arguments in the remaining of typle.

like image 152
Serge Ballesta Avatar answered Sep 27 '22 15:09

Serge Ballesta