The Illustrated Zen of Python vol. 1 - Beautiful is Better than Ugly

zensorflow izop 1.jpg

Python is a versatile, high-level programming language that works great for data science. The best thing about Python is that it’s easy to get started with. If you’re clever enough to drive stick, you too can build something useful with Python. However, while writing functional Python code is quite intuitive, writing truly beautiful code takes time, practice, and guidance.

Beautiful code is a rare breed of poetry. It’s easier to feel the qualities of beautiful code than to describe them. Tim Peters, a noted Pythonic paragon, left us some helpful breadcrumbs to follow in the form of his essential design principles: The Zen of Python. These pithy koans are so wildly popular in the Python community that they were hidden as an Easter Egg. Any time you wish to review them, simply type ‘import this’ into your Python interpreter and they’ll pop up.

The first aphorism of The Zen of Python is “Beautiful is Better than Ugly” let’s take a look at what that means in practice. Do your best to read the two examples below, don’t worry about what they mean, just read them.

code sample 1.jpg

Both these examples are true and say the same thing, but the second example is markedly easier to read. Beautiful Python code should require as little thinking as possible on behalf of the reader. That means using logical operators like ‘and’ and ‘or’ rather than ‘&&’ or ‘||’ respectively as one might in other languages. It’s not only efficiency that Pythonic developers strive for, it’s clarity.

Here’s another two examples to ponder. Both of these examples aim to take a list object called ‘my_list’ and print a new list that adds one to each element in the original list. Again, don’t bother trying to understand exactly what each line of code says, just scan through them quickly and ask yourself which one is more beautiful.

code sample 2 (better).jpg

Example one, while interesting from a systems perspective, is clearly uglier. Conversely, even someone with no background in coding could probably sniff out the gist of example two.  If they were to apply a little thought, they could probably even decipher the meaning of each aspect of that one line of code and even change it to suit their purposes. All that without cracking open a textbook or looking up the documentation online. Code that confers meaning which transcends language and explains itself even as it performs its function, that’s a rare breed of poetry indeed. Write like that.

For more reading on developing beautiful Python code, we suggest you peruse the official Python Developer’s Guide and The Hitchhiker’s Guide to Python.  Good luck!