-1

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 ?

Aion
  • 620
  • 1
  • 6
  • 25
  • you can remove the inner conditions by just doing `doActionA(collection)` (same for `doActionB`) –  Mar 24 '22 at 16:17
  • It might be better to drop this question on https://codereview.stackexchange.com/ with some more context. – matszwecja Mar 24 '22 at 16:21
  • Similar question: https://stackoverflow.com/questions/64168905/are-there-a-way-to-use-while-loop-function-as-a-list-tracker-and-mix-with-filei/ – Stef Mar 24 '22 at 16:31

2 Answers2

1

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])
Stef
  • 13,242
  • 2
  • 17
  • 28
0

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)
Robert
  • 307
  • 2
  • 9