2

I found the short article Align the happy path to the left edge quite helpful in improving readability of functions. Briefly, reading down the left edge of the function should step you through the logic of the happy path scenario. Errors and special cases are nested in conditionals, or decanted into separate functions.

The article was written with Go in mind but I believe this approach could be applied to other languages, Python in particular. But do any of the guidelines below, taken directly from the article, break Python conventions (sometimes called Pythonic idioms)?

  1. Align the happy path to the left; you should quickly be able to scan down one column to see the expected execution flow.

  2. Don’t hide happy path logic inside [nested indents]

  3. Exit early from your function

  4. Avoid else returns; consider flipping the if statement

  5. Put the happy return statement as the very last line

  6. Extract functions and methods to keep bodies small and readable

  7. If you need big indented bodies, consider giving them their own function

I don't think 5, 6 or 7 are at all controversial. Are there existing guidelines or conventions that contradict any of 1-4?

lofidevops
  • 271
  • 1
  • 11

1 Answers1

5

There are no strong Python conventions such as PEP-8 about any of this. Some tools like Pylint will complain about useless else-clauses (item #4) or about excessively convoluted control flow.

I think there is a strong language-independent argument for what you call the “happy path to the left edge”. Previously, tradeoffs of different code layouts were considered on this site under Approaches for checking multiple conditions and its linked questions.

One notable drawback of structuring the code with a linear happy path is that the guard conditions will often feature negations of the form “if this isn't the expected case, then return”. Such negations can make the code more difficult to read. Within reason, there's nothing fundamentally wrong with nesting – but there is something wrong with following one “best practice” or another when it makes the code more difficult to read.

amon
  • 135,795