Search code examples
pythondesign-patternsidiomsreadability

Better pythonic idiom for this repeated piece code pattern


I find myself using this code pattern quite a bit, and every time I do I think there might be a better, clearer way of expressing myself:

do_something = True

# Check a lot of stuff / loops
for thing in things:
    ....
    if (thing == 'something'):
        do_something = False
        break

if (do_something):
    # Do something

So essentially, "plan on doing something but if this particular condition is found anytime, anywhere, don't do it"

Maybe this code is perfectly fine, but I wanted to see if anyone had a better suggestion.

Thanks for any input


Solution

  • Python for loops can have an else block, which is executed if those loop is not broken out of:

    for thing in things:
        ...
        if (thing == 'something'):
            break
    else:
        ... # Do something
    

    This code will work in the same way as yours, but doesn't need a flag. I think this fits your criteria for something a bit more elegant.