On 01/21/2011 05:33 PM, Ed Connell wrote:
Consider the following please:  (re_section, re_name, etc are previously
compiled patterns)

                        result1 = re_section.search(line);
                        result2 = re_name.search(line);
                        result3 = re_data1.search(line);
                        result4 = re_data2.search(line);

                        if result1:
                                last_section = result1.group()[18:-5]
                        elif result2:
                                last_name = result2.group(0)[6:-1]
                        elif result3:
                                data[last_section] = {last_name:
result3.group()[13:-5]}
                        elif result4:
                                data[last_section] = {last_name:
result4.group()[17:-5]}

It gets my goat to have to obtain all resultx when I just want the first
that is not None.  (In theory, the number of results can be much longer.)

The problem isn't so much the elif structure, but that you're doing different things with each result. If they were attributes of a class and value assignments (instead of top-level variables, sometimes calling .group() with no params & sometimes with "0", and a mix of strings/dicts), you could do something like

  line = "..."
  info = object() # some class with attributes to update
  for name, r, slc in (
      ("section", re_section, slice(18,-5)),
      ("name", re_name, slice(6,-1)),
      ("data1", re_data1, slice(13,-5)),
      ("data2", re_data2, slice(17,-5)),
      ):
    result = r.search(line)
    if result:
      setattr(info, name, result.group(0)[slc])
      break
  else:
    woah_none_matched(fail, fail, fail, do_I_care)

So if you're doing predictable things with each, it's not too bad.

-tkc



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to