[Tutor] How to put my functions in an array
Mohamed Lrhazi
mohamed at your-site.com
Thu Dec 30 14:40:25 CET 2004
On Thu, 2004-12-30 at 03:08, Alan Gauld wrote:
>
> I'm slightly confused about why you need to do this?
> You create a list of names (PROVISION_ACTIONS), then
> you add the corresponding functions to a dictionary
> by looking the names up in the globals dictionary.
> But since uyou know the names of the functions why
> not just add them to the actions list in the first place?
Alan,
I know I know... I dont know what am doing :)
I am writing a little web application, with my PHP brain... uri's like:
?action=addvirt ?action=remvirt and so on....
In PHP, I'd have a swtich action, case 'addvirt': addvirt()
I know Python can do better, so I wanted to replace that huge if elif
elif... with:
if we have a handler for the action, duh, call the action... so in a
module (a file) I have all these functions defined... at the end of that
file, I have:
formhandlers={}
for verb in ('addvirt','remvirt',):
try:
formhandlers[verb]=globals()[verb]
except KeyError
pass
Now in my Nevow code where I handle the incoming request:
if action:
try:
return formhandlers[action](context)
except KeyError:
return T.div(_class='error')['Unsupported Action Requested:
%s'%action]
I realize now that I dont even need a array(dictionary) to hold the
references to my fucntions... they are always there, and I can try to
access them anytime, except for KeyErrors where I'd know I did not write
that handler yet :)
Thanks all...
Mohamed~
More information about the Tutor
mailing list