4 ms·
> Python's "enforcement" (or rather, strong PEP-8 suggestions) of 80 characters per line teaches you to come up with a lot of ways to avoid nesting. > The mos
by thaumasiotes 11y ago
> Python's "enforcement" (or rather, strong PEP-8 suggestions) of 80 characters per line teaches you to come up with a lot of ways to avoid nesting.
> The most useful one, and the one that drives me crazy when I see it, is when people write code like this:
But... your example doesn't show any ways to avoid nesting. There's just as much nesting after as before.
Your change makes the code less tall, which is a problem I've had with Python, but it has nothing to do with nesting at all.
I'm actually fond of a third approach:
if something:
return do something
else:
return do something else
I like the ocaml-style philosophy that it's an error if your condition check isn't capable of handling all possible conditions.
- oneeyedpigeon 11y agoTernary operator to the rescue: return something ? do_something () : do_something_else();
- johnmaguire2013 11y agoI figured readers could fill in the relevant blanks. Updated example: if something: value = do something else: if something_else: value = do something else else: value = do a third thing As I said in my initial post, "it helps once you have nested ifs, and multiple lines of code." Here's the change: if something: return do something if something_else: return do something else return do a third thing Again, what I'm stressing here is that if you already have your result, you can return, and it makes the code easier to follow than adding a superfluous "else:" statement.