python - How can I better structure this code? -
i have lxml.objectify data structure restful web service. need change setting if exists , create if doesn't. right have along lines of following, feel it's ugly. structure i'm looking in has list of subelements have same structure, can't specific tag unfortunately.
thing_structure = lxml.objectify(get_from_rest_service()) found_thing = false if thing_structure.find('settings') not none:     i, foo in enumerate(thing_structure.settings):         if foo.is_what_i_want:             modify(thing_structure.settings[i])             found_thing = true if not found_thing:     new = lxml.etree.subelement(thing_structure, 'setting')     modify(new)  send_to_rest_service(thing_structure)      
overall, structure isn't bad (assuming need call modify on 1+ items in settings -- if "just one", i.e., if is_what_i_want flag going set 1 setting @ most, that's of course different, , should use break for loop -- that's not impression of intentions q, please clarify if i've mistead!).  there's 1 redundancy:
for i, foo in enumerate(thing_structure.settings):     if foo.is_what_i_want:         modify(thing_structure.settings[i])         found_thing = true   having i , using again same foo no use here, can simplify to:
for foo in thing_structure.settings:     if foo.is_what_i_want:         modify(foo)         found_thing = true   you'd need index if rebind item, i.e., perform assignment such thing_structure.settings = whatever.  (btw, name other foo wouldn't hurt;-).
Comments
Post a Comment