Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best way to format conditionnal statement

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading