exit 2 levels of if/else and execute common code

Cameron Simpson cs at cskk.id.au
Mon Feb 11 20:53:07 EST 2019


On 11Feb2019 08:17, Irv Kalb <Irv at furrypants.com> wrote:
>> On Feb 11, 2019, at 7:25 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?
>>
>
>I like the additional function approach others have mentioned.  But if you want a different approach, you could do this:
>
>runExtraCode = True    # set some Boolean
>if cond1:
>    [some code]
>    if cond2:
>        [more code]
>        runExtraCode = False  # both conditions met, no need to run the extra code
>
>if runExtraCode:
>    [do xxyy]

I want to second this. As others have said, there's a trivialness 
threshold where you wouldn't bother, and that is subjective. But when 
you do, the above is often useful. If "runExtraCode" bothers you, 
consider "need_task", with a suitable "task" name.

I've got several things in the above form. The most recent I fiddled 
with was last night, in a monitor script which updates some information.  
It takes the form:

  updated = False
  while True:
    time.sleep(INTERSCAN_DELAY)
    for rpath, dirnames, filenames in os.walk(...):
      ...
      for filename in filenames:
        if new file found:
          scan file ...
          updated = true
      if updated:
        update top level record ...
        updated = False
      ...

which updates a state file on a per subdirectory frequency if something 
new is found. This falls into exactly the pattern Irv describes.

You'll notice my example starts with the flag variable being False, and 
makes it True if the extra code should run. I personally prefer that 
pattern (I like things to generally start False, or zero, or empty), but 
what values you use will depend on what you're doing.

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list