Issue
I have the following conditionnal statement :
if(action == 'actionA'):
if(collection == 'collectionA'):
doActionA(collectionA)
elif(collection == 'collectionB'):
doActionA(collectionB)
if(action == 'actionB'):
if(collection == 'collectionA'):
doActionB(collectionA)
elif(collection == 'collectionB'):
doActionB(collectionB)
This code seems really poor designed, is there a better pythonical way to do it ?
Solution
The classic way to "choose" an element depending on its name is to use a dictionary. Dictionaries can hold any kind of objects, including functions.
collections = {'collectionA': collectionA; 'collectionB': collectionB}
doActions = {'actionA': doActionA; 'actionB': doActionB}
# do action, without error checking
doActions[action](collections[collection])
# do action, with default value
doActions.get(action, doDefaultAction)(collections.get(collection, defaultCollection))
# do action, only if values are correct
if action in doActions and collection in collections:
doActions[action](collections[collection])
Answered By - Stef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.