exit 2 levels of if/else and execute common code

Neal Becker ndbecker2 at gmail.com
Mon Feb 11 11:34:03 EST 2019


Chris Angelico wrote:

> On Tue, Feb 12, 2019 at 3:21 AM Neal Becker <ndbecker2 at gmail.com> wrote:
>>
>> Chris Angelico wrote:
>>
>> > On Tue, Feb 12, 2019 at 2:27 AM Neal Becker <ndbecker2 at gmail.com>
>> > wrote:
>> >>
>> >> I have code with structure:
>> >> ```
>> >> if cond1:
>> >>   [some code]
>> >>   if cond2: #where cond2 depends on the above [some code]
>> >>     [ more code]
>> >>
>> >>   else:
>> >>     [ do xxyy ]
>> >> else:
>> >>   [ do the same xxyy as above ]
>> >> ```
>> >>
>> >> So what's the best style to handle this?  As coded, it violates DRY.
>> >> Try/except could be used with a custom exception, but that seems a bit
>> >> heavy
>> >> handed.  Suggestions?
>> >
>> > One common way to do this is to toss a "return" after the cond2 block.
>> > Means this has to be the end of a function, but that's usually not
>> > hard. Or, as Rhodri suggested, refactor xxyy into a function, which
>> > you then call twice.
>> >
>> > ChrisA
>>
>> Not bad, but turns out it would be the same return statement for both the
>> normal return path (cond1 and cond2 satisfied) as well as the abnormal
>> return, so not really much of an improvement.
> 
> Not sure what you mean there. The result would be something like this:
> 
> def frobnicate():
>     if cond1:
>         do_stuff()
>         if cond2:
>             do_more_stuff()
>             return
>     do_other_stuff()
> 
> ChrisA
sorry, I left out the return:

if cond1:
   [some code]
   if cond2: #where cond2 depends on the above [some code]
     [ more code]

   else:
     [ do xxyy ]
else:
   [ do the same xxyy as above ]
return a, b, c

So if we return normally, or return via some other path, the return 
statement is the same, and would be duplicated.




More information about the Python-list mailing list