Why is Flat Better Than Nested? (Zen of Python)

By on 1 August 2023

The short answer: deeply nested code can be hard to read and understand (and this not only applies to Python, but for any code really).

Each level of indentation adds a level of complexity and an additional condition that the reader (which is often you!) has to keep in their head while trying to understand the code.

Here is an example of deeply nested code and how we can refactoring it to make it more readable (and therefor maintainable):

1689085744284

In the refactoring we reduce the level of nesting by using “early returns”.

Instead of nesting conditions, you can invert the conditions and return early.

This version of the function does exactly the same thing as the first one, but it’s easier to read because there’s less nesting.

It’s also easier to modify because you don’t have to find the right level of indentation to add or change a condition.

So remember to keep your code flat and simple to make it easier to read and maintain. Your team and your future you will thank you for it 🙂

You can practice this + other refactoring techniques in our refactoring Bite exercise -> promo code (valid till the 31st of August 2023).

And for more reflections on the Zen of Python, check out this article.

Happy (clean) coding!

Want a career as a Python Developer but not sure where to start?