Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

For instance, I've tried things like mydict = {'funcList1': [foo(),bar(),goo()], 'funcList2': [foo(),goo(),bar()], which doesn't work.

Is there some kind of structure with this kind of functionality?

I realize that I could obviously do this just as easily with a bunch of def statements:

def func1():     foo()     bar()     goo() 

But the number of statements I need is getting pretty unwieldy and tough to remember. It would be nice to wrap them nicely in a dictionary that I could examine the keys of now and again.

like image 492
Zack Avatar asked Feb 09 '12 03:02

Zack


People also ask

Can you store function in a list?

Functions can be stored as elements of a list or any other data structure in Python.

Can we store function in dictionary?

Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.

Can we store functions in a list Python?

Yes. Because these data structures are ordered and indexed, a Python list can contain any number of repeated items.


1 Answers

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']) 
like image 147
Praveen Gollakota Avatar answered Sep 20 '22 18:09

Praveen Gollakota