samedi 17 mars 2018

python conditional statements optimization

Can you please help me optimize this code I wrote? I have a function that parses an XML, but... the field I'm intending to save (address) might be either an IP or domain address and depending which is it, I want to save it to a different file, by calling the same function with different arguments. As you can see I used sort of "python switch", but I don't like that way.

Any ideas?

@staticmethod
def parse(xmlroot, filename, xml_node, xml_attrib):
    feed_list = []

    def address():
        if (nested.attrib[xml_attrib] + "\n") not in feed_list and rg.search(nested.attrib[xml_attrib]):
            feed_list.append(nested.attrib[xml_attrib] + "\n")

    def others():
        if (nested.attrib[xml_attrib] + "\n") not in feed_list:
            feed_list.append(nested.attrib[xml_attrib] + "\n")

    parse_options = [address, others]

    with open(output + filename, "w") as file:
        for nested in xmlroot.iter(xml_node):
            if xml_node == "net" and xml_attrib == "address":
                parse_options[0]()
            else:
                parse_options[1]()
        feed_list_sorted = sorted(feed_list)
        file.writelines(feed_list_sorted)

Aucun commentaire:

Enregistrer un commentaire