[Tutor] How to put my functions in an array

Alan Gauld alan.gauld at freenet.co.uk
Thu Dec 30 09:00:41 CET 2004


I'm not sure what exa ctly you are trying to do here,
but I'll take a guess.

> def addvirt(): pass
> def remvirt(): pass
> PROVISION_ACTIONS=[('addvirt','Add Virt'),('remvirt','Remove
Virt'),]

Not sure why you have the list of tuples of strings, but it
shouldn't be a problem.

> formhandlers={}
>
> # this works
> formhandlers["addvirt"]=addvirt
> formhandlers["remvirt"]=remvirt

So now you have a dictionary keyed by verb and holding the functions.

> # this does not work:
> for verb,verb_desc in PROVISION_ACTIONS:
> if callable(verb):

your verbs are strings so they won't be callable.

> formhandlers[verb]=verb

and this overwrites the function with the string???

I think what you might want is:

for verb,verb_desc in PROVISION_ACTIONS:
    formhandlers[verb]()

which calls each of the functions in turn.

However considering the message subject says you
want the functions in an array, you could do that with:

myarray = [addvirt, remvirt]

and iterate over it with:

for action in myarray:
   action()

I'm not sure I've answered your question but I hope it helps!

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list