[Tutor] How to put my functions in an array

Jeff Shannon jeff at ccvcorp.com
Wed Dec 29 20:37:14 CET 2004

Mohamed Lrhazi wrote:

> def addvirt():
> 	pass
> def remvirt():
> 	pass
> PROVISION_ACTIONS=[('addvirt','Add Virt'),('remvirt','Remove Virt'),]
> formhandlers={}
> # this works
> formhandlers["addvirt"]=addvirt
> formhandlers["remvirt"]=remvirt
> # this does not work:
> for verb,verb_desc in PROVISION_ACTIONS:
> 	if callable(verb):
> 		formhandlers[verb]=verb
> I tried a few different syntaxes but to no avail... do I need things
> like: getattr()? 

You don't say how this fails, which would be very helpful to know. 
But I think I can guess what's happening.

When you're calling 'callable(verb)', at this point verb contains a 
string which is a function's name.  It is *not* the function itself. 
The string is, of course, not callable, so nothing gets added to 

Even if you took out that test, though, you'd end up with a dictionary 
  where for a given key, the value is the same string that was used 
for the key, because verb is only a string.

For this to work, you need to have two separate things -- a string by 
which to identify the function, and a reference to the function object 
itself.  In the working code, you do this.  By putting the name (that 
you're using as the dictionary key) in quotes, you're specifying a 
string, and by *not* putting the value (on the right of the = sign) in 
quotes, you're referring to the function object.

There's a couple of ways you can do this.  One is by adding a 
reference to the function to your list, something like this:

     PROVISION_ACTIONS = [('addvirt', "Add Virt", addvirt), ...]

     for verb, verb_desc, func in PROVISION_ACTIONS:
         if callable(func):
             formhandlers[verb] = func

If you can't make that change to PROVISION_ACTIONS, then you may be 
able to use the name strings to pull function references from your 
module's global dictionary --

     for verb, verb_desc in PROVISION_ACTIONS:
         func = globals()[verb]
         if callable(func):
             formhandlers[verb] = func

though you'd probably want to put that globals() lookup in a 
try/except block to catch any KeyErrors.

Note that if the functions were in a different module, you could 
retrieve them from that module with getattr(), rather than using the 
globals() dict.

     import func_module
     # ...
     for ...
         func = getattr(func_module, verb)
         # ...

Once again, you should probably wrap that in a try/except block (this 
time looking for AttributeErrors).

Jeff Shannon
Credit International

More information about the Tutor mailing list