I have this piece of code (should be self-explanatory; if not, just ask):
for tr in completed_taskrevs:
found = False
for nr in completion_noterevs:
if tr.description in nr.body:
completion_noterevs.remove(nr)
found = True
break
assert found
How can I make it more pythonic?
Using
assert/AssertionErroris probably wrong here, I’d say. It’s useful for “debugging assertions”, which is to say, to make sure your code is sane. It’s not useful as a way to raise an error when you get invalid data, for many reasons, the most interesting of which is probably that assert isn’t even guaranteed to be executed– if your code is compiled with any optimization settings, it won’t be. And heck, even if this is a debugging thing, I’d still use raise– it’s more readable, and it’ll always happen, no matter when or why the data is wrong.So to make it more “pythonic”, I would remove the assert and replace it with something nicer. As it happens, such a nicer thing exists, and it’s the
raisestatement. Further, I would replace the clumsy value set/check with the else clause of loops, which is executed when the loop is exhausted (or, for while loops, when the condition becomes false). So if you break, the else clause is not executed.Other than this, I probably wouldn’t change anything.