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 ?
CodePudding user response:
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])
CodePudding user response:
If this is it, i.e. no other actions and collections are possible, combine your statements:
if(
action == 'actionA' and
collection == 'collectionA'
):
doActionA(collectionA)
elif(
collection == 'collectionB'
):
doActionA(collectionB)
if(
action == 'actionB' and
collection == 'collectionA'
):
doActionB(collectionA)
elif(
collection == 'collectionB'
):
doActionB(collectionB)