python - better maintainable way to combine strings from multiple options -


i have scenario user can pass in multiple options. each option passed in, text , merge text multiple options , return single string. here how i'm doing 3 options accept today. code looks unmaintainable , add more options, logic worse:

if (len(self.options.passedin.split(",")) > 0): #multiple options passed in   ops = self.options.passedin.split(",")   op in ops:      if (op == "option1"):          op1_text = get_text_for_option1()      elif (op == "option2"):          op2_text = get_text_for_option2()      elif (op == "option3"):          op3_text = get_text_for_option3()     #all 3 passed in    if ("option1" in ops , "option2" in ops , "option3" in ops):       op1_op2 = op1_text + " " + ' '.join(w w in op1_text.split() if w not in op2_text.split())       op3_op1_op2 = op1_op2 + " " + ' '.join(w w in op1_op2.split() if w not in op3_text.split())       return op3_op1_op2    #option1 , option2 passed in    elif ("option1" in ops , "option2" in ops , "option3" not in ops):       return op1_text + " " + ' '.join(w w in op1_text.split() if w not in op2_text.split())    #option1 , option3 passed in    elif ("option1" in ops , "option3" in ops , "option2" not in ops):       return op1_text + " " + ' '.join(w w in op1_text.split() if w not in op3_text.split())    #option2 , option3 passed in    elif ("option2" in ops , "option3" in ops , "option1" not in ops):       return op2_text + " " + ' '.join(w w in op2_text.split() if w not in op3_text.split()) 

the methods get_text_for_option1 get_text_for_option2 get_text_for_option3 can't combined.

use dict map option names appropriate function returns option text, join together, take unique words, eg:

from collections import ordereddict  options = {     'option1': get_text_for_option1,     'option2': get_text_for_option2,     'option3': get_text_for_option3 }  input_text = 'option3,option1,option2'  all_text = ' '.join(options[opt]() opt in input_text.split(',')) unique = ' '.join(ordereddict.fromkeys(all_text.split())) 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -