Short circuting

Alexander Kapps alex.kapps at web.de
Fri Jan 21 19:10:41 EST 2011


On 22.01.2011 00:33, Ed Connell wrote:
> Hi,
>
> 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.)  I can think of alternatives (raising exceptions), but
> they all use deep indenting.
>
> Ideas?
>
> Ed
>


Maybe something like this (totally untested and probably wrong, I'm 
already quite tired):


for pattern in (re_section, re_name, re_data1, re_data2):
     result = pattern.search(line):
     if result:
         if pattern == re_section:
             last_section = result1.group()[18:-5]
         elif pattern == re_name:
             last_name = result2.group(0)[6:-1]
         elif pattern == re_data1:
             data[last_section] = {last_name: result3.group()[13:-5]}
         elif pattern == re_data2:
             data[last_section] = {last_name: result4.group()[17:-5]}


Also, if you have long if/elif ladders, look if you can apply the 
dictionary dispatch pattern.



More information about the Python-list mailing list