Get the highlights in your inbox every week.
Why your Python code needs to be beautiful and explicit | Opensource.com
Why your Python code needs to be beautiful and explicit
Welcome to Pythonukkah, a special series about the Zen of Python. On the first day, we celebrate the first two principles: beauty and explicitness.
Python contributor Tim Peters introduced us to the Zen of Python in 1999. Twenty years later, its 19 guiding principles continue to be relevant within the community. We start our Pythonukkah celebration—like Hanukkah, a festival of lights—with the first two principles in the Zen of Python: on beauty and explicitness.
"Hanukkah is the Festival of Lights,
Instead of one day of presents, we get eight crazy nights."
—Adam Sandler, The Hanukkah Song
Beautiful is better than ugly.
It was in Structure and Interpretation of Computer Programs (SICP) that the point was made: "Programs must be written for people to read and only incidentally for machines to execute." Machines do not care about beauty, but people do.
But even more important, only humans can judge what humans find beautiful. Code reviews and a collaborative approach to writing code are the only realistic way to build beautiful code. Listening to other people is an important skill in software development.
Finally, all the tools and processes are moot if the will is not there. Without an appreciation for the importance of beauty, there will never be an emphasis on writing beautiful code.
This is why this is the first principle: it is a way of making "beauty" a value in the Python community. It immediately answers: "Do we really care about beauty?" We do.
Explicit is better than implicit.
We humans celebrate light and fear the dark. Light helps us make sense of vague images. In the same way, programming with more explicitness helps us make sense of abstract ideas. It is often tempting to make things implicit."Why is self explicitly there as the first parameter of methods?"
There are many technical explanations, but all of them are wrong. It is almost a Python programmer's rite of passage to write a metaclass that makes explicitly listing self unnecessary. (If you have never done this before, do so; it makes a great metaclass learning exercise!)
The reason self is explicit is not because the Python core developers did not want to make a metaclass like that the "default" metaclass. The reason it is explicit is because there is one less special case to teach: the first argument is explicit.
Even when Python does allow non-explicit things, such as context variables, we must always ask: Are we sure we need them? Could we not just pass arguments explicitly? Sometimes, for many reasons, this is not feasible. But prioritizing explicitness means, at the least, asking the question and estimating the effort.