Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 867
cemulate Avatar asked Jan 13 '23 09:01

cemulate


1 Answers

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.

like image 50
Gareth Latty Avatar answered Jan 19 '23 08:01

Gareth Latty