3 ms·
Early returns are very useful, just like break/continue. For example, I find it much easier to write for filename in os.listdir(dirname): if not fi
by nneonneo 3y ago
Early returns are very useful, just like break/continue. For example, I find it much easier to write
for filename in os.listdir(dirname):
if not filename.endswith(".png") and not filename.endswith(".jpg"):
continue
# process a png or jpg image
than to try and have a nested `if filename.endswith(".png") or filename.endswith(".jpg")`, particularly as it drops one nesting level and is easier to read. Unfortunately, Python lacks targeted break/continue so you can't break out of two nested loops without some contortions; in such cases, I find it useful to refactor code into smaller functions just to be able to use early return from a nested context.
- Already__Taken 3y agothe early return solution to this would be to filter os.listdir before the loop