5. WRITING PY THONIC CODE

Powerful is a meaningless adjective for pro- gramming languages. Every programming language describes itself as powerful: the official Python Tutorial begins with the sen- tence “Python is an easy to learn, powerful program- ming language.” But there’s no algorithm that one language can do that another can’t, and no unit of measurement to quantify a programming language’s “power” (although you certainly can measure the vol- ume at which programmers argue for their favorite language).

But every language does have its own design patterns and gotchas that make up its strengths and weaknesses. To write Python code like a true Pythonista, you’ll need to know more than just the syntax and standard library. The next step is to learn its idioms, or Python-specific coding prac- tices. Certain Python language features lend themselves to writing code in ways that have become known as pythonic.

In this chapter, I’ll provide several common ways of writing idiomatic Python code along with their unpythonic counterparts. What counts as pythonic can vary from programmer to programmer, but it commonly includes the examples and practices I discuss here. Experienced Python programmers use these techniques, so becoming familiar with them allows you to recognize them in real-world code.