Flat-nested/sparse-dense

The part about flat being better than nested, in particular, is a reason for those famous one-line Python codes that you see. Simple code shouldn’t have to span across 20-30 lines when it can be done in a few. In a lot of languages, it cannot be done in a few lines, but in Python, it can.

Let’s test out this concept when printing each value for this array: my_list = [1,2,3,4,5]:

Flat and sparseNested and dense
print(*my_list)for element in my_list: print(element)

Table 2.1 – Flat and sparse versus nested and dense

Again, a very small example, but one of many present in the Python language. I recommend going through the list of libraries that Python comes pre-installed with; it is a very interesting read and will help you come up with a lot of ideas.

A lot of the time, this flat and sparse concept reduces the amount of code written by a significant amount. In turn, this makes the code more readable just from the reduced time it takes to read the code.

Let’s dive into readability and the purity of the concept.

Readability-special cases-practicality-purity-errors

Python is meant to be a language that can be read and understood at some level by the layperson. It doesn’t require any particularly special syntax and even the one-liners can be interpreted quite easily. Readability counts, and there are no special cases that are special enough to violate this credo. I have already expressed both philosophies through the previous examples, so there is no need to reiterate them here.

Practicality over purity is a fairly simple concept. Often, trying to follow best practices too strictly simply results in a waste of time. Sometimes, the best way to do something is to do it and then explain it later. However, in such cases, make sure that your boldness doesn’t result in something that might break the system. In that case, try-catch error handling is your best friend. It also helps to pass errors silently when you need it to.

Balance between the two – progress and verification – results in code that has been verified and tested, but also code that is actually shipped to the end user. This balance is integral to any successful project. You have to be pragmatic when you are doing actual work, but you also have to realize that other people may not be so pragmatic in their actions and their estimates.

To take action in either direction, pragmatism or purity requires a sense of direction. It requires deciding something or some way and sticking to it.