4

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

cemulate
  • 2,305
  • 1
  • 34
  • 48

1 Answers1

9

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.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • Never seen this before...interesting. I wonder if this would be confusing to read though if my lack of knowledge is typical? – YXD May 11 '13 at 17:30
  • 1
    @MrE If someone hasn't come across it before, the docs explain it well. I don't see any reason to avoid using it. It's more readable than using a flag, and it's pretty well known amongst Python programmers. – Gareth Latty May 11 '13 at 17:31
  • 2
    What I mean is that my first instinct would have been to assume the code was incorrectly indented rather than to look it up. Ignorance isn't a good reason to avoid the right answer though, +1 – YXD May 11 '13 at 17:32
  • @MrE I see. The `if` at the end makes that a little more of an issue in this case, but in general, I think the fact it ran fine as is would alert someone that it wasn't incorrect indentation (otherwise it would be a Syntax Error). Beyond that, limiting yourself to features of the language that are known by everyone is massively restrictive. – Gareth Latty May 11 '13 at 17:34
  • @Lattyware ignore my rambling, I'm confusing myself :) – YXD May 11 '13 at 17:38
  • Thanks, I wasn't aware of this feature either! – cemulate May 11 '13 at 17:52