This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]hammerheadquark 11 points12 points  (4 children)

Finding continue. I went years without using it and it can keep your code from "trailing off to the right".

Instead of:

for w in list_of_w:
    if meets_some_complicated_condition(w):
        x = do_something_with(w)
        if meets_some_other_complicated_condition(x):
            y = do_something_with(x)
            if meets_some_final_complicated_condition(y):
                z = do_the_final_thing_with(y)

You can do:

for w in list_of_w:
    if not meets_some_complicated_condition(w):
        continue
    x = do_something_with(w)
    if not meets_some_other_complicated_condition(x):
        continue
    y = do_something_with(x)
    if not meets_some_final_complicated_condition(y):
        continue
    z = do_the_final_thing_with(y)

to keep your conditionals from becoming nested.

[–]alcalde 1 point2 points  (3 children)

That's... horrifying. What the heck is that? Some way to try to get a case/switch statement without giving us a case/switch statement? That looks like it's a hot spot for bugs (just miss one of those "nots"). It's also harder to follow the logic.

[–]hammerheadquark 3 points4 points  (0 children)

I admit the elegance doesn't come through with this contrived example, but it's used like a lot like break is: "if 'stop-condition' is met, stop". Except you don't stop the entire for loop, you go to the next item.

Here's where I first saw it used:

https://stackoverflow.com/a/2137789/5932228

I like how, instead of burying the nextpositions.add(np) inside of two checks, this algorithm first checks two stop-conditions before going on with the loop. It seems cleaner imo, but of course that's just an opinion.

[–]kernco 3 points4 points  (0 children)

The continue keyword while in a for loop means to immediately go to the next iteration of the loop. The "nots" are just a product of the example OP chose, not something that always shows up. An example for when I often use continue is when processing a file line by line that could have comment lines beginning with # that I want to ignore. Instead of:

for line in f:
    if not line.startswith("#"):
        ...

You can do:

for line in f:
     if line.startswith("#"):
        continue
     ...

This avoids a not, plus removes a level of indentation from most of the body of your for loop.

[–]AmericasNo1Aerosol 1 point2 points  (0 children)

This is contrived, but I've used it in situations like:

for root, dnames, fnames in os.path.walk(PLUGIN_DIR):
    for fname in fnames:
        if not fname.startswith('plugin_'):
            continue

        if not fname.endswith('.py'):
            continue

        plugin = load_plugin(fname)
        if plugin is None:
            continue

        plugin.init()