Last Updated on
When browsing Stack Overflow for answers to your programming questions, you’ve likely come across charges against certain code as “unpythonic,” or praise of one solution as “more Pythonic” than another. But what do developers mean by these terms? In this article, we’re going to take a look at Pythonic style, first defining it and then showing you how you can — and why you should — learn about it.
From Python Syntax to Pythonic Style
In short, “pythonic” describes a coding style that leverages Python’s unique features to write code that is readable and beautiful. To help us better understand, let’s briefly look at some aspects of the Python language.
Since its first release in 1991, Python has become the most popular general-purpose programming language. Thanks to its transparency and readability, it is suitable for beginners. Even those with limited programming knowledge can look at a piece of Python code and understand what it does.
Interestingly, it’s not necessarily the complete beginner who produces code that may be deemed “unpythonic.” This can happen when a programmer has a background in another language. They’ll write Python code that works, but which may really be just a literal translation from their “native” language. This is basically the code equivalent to “yes, you could say that — but you wouldn’t.”
Let’s look at two practical examples!
A tuple is similar to a list except that it’s immutable, meaning that you cannot modify it. Sometimes a function will return a tuple of items that we want to unpack for its contents. Here’s how you could do it:
This solution certainly works, and it would be correct in a language like C. Python, however, has a feature called multiple assignment. Instead of indexing, you can just assign all the variables in one line, and Python will unpack the tuple for you:
Neat, isn’t it? And decidedly Pythonic! Next, let’s look at an all-time favorite syntactic feature.
Say you have a list of names that are written out in different ways, and you want to convert them all to follow standard name capitalization. One way in which you could do it is with a for loop:
It worked! But what if I told you there’s another solution that is both shorter and more readable? Enter list comprehensions:
Pythonic Style Guidelines
But how can you get to know all of Python’s handy features and quirks, especially as a beginner? Thankfully, the Python developer community has assembled a set of Pythonic style guides. These come in the form of “Python Enhancement Proposals”, or PEPs for short.
The Zen of Python (PEP 20)
The Zen of Python is listed as PEP 20. It’s a collection of 19 statements (number 20 is missing) that describe a certain philosophy to follow when coding in Python. You can find PEP 20 here or as an easter Egg in the Python console, by typing import this.
The first lines of the Zen of Python read as follows:
The list continues in the same vein, but nearly all the 19 aphorisms may be read as expressions of line number seven, which states:
If this statement is beginning to sound like a mantra, you’re not wrong. But it’s meant to remind us that code is intended to be read, understood and used. This was Guido van Rossum’s insight when he started designing the Python language, and it’s something every Python programmer should keep in mind.
PEP 8 is the style guide for Python, with guiding principles for almost everything from naming to spacing, and plenty of practical examples along the way. It is cited extensively in discussions about style and forms the coding standard at many companies.
However, it’s important to note that we’re dealing with guidelines, not requirements. PEP 8’s authors emphasize that there are cases in which the guide may be disregarded. One example is when your project or workplace has specific Python style requirements that contradict PEP 8.
One of the most contested PEP 8 guidelines is the maximum length of 79 characters per line. It was introduced to avoid ugly line wrapping when reviewing code with two windows side-by-side.
But forcing people to stick to a static number can cause readability compromises, for the sake of complying with the standard. This in turn contradicts an important PEP8 principle which states “A Foolish Consistency is the Hobgoblin of Little Minds.” For more on this point, watch Raymond Hettinger’s illuminating PyCon talk titled “Beyond PEP 8.
Other PEP 8 guidelines are less contested and have become standard practice among Python programmers. Take naming conventions for example. The style guide states that variables shouldn’t receive names that look like the integers 0 or 1, while functions and methods should be written in snake_case and classes in CamelCase.
This PEP is only for docstrings (i.e., documentation that is written directly in your code). You may read it here.
Pythonic Style Tools
At this point you might ask yourself: Isn’t there a way to automate all of this? Of course there is. In this section, we’ll look at some tools to help you with your Pythonic style. First up: linters!
Linting refers to the process of automatically checking your code for errors and stylistic mistakes. A linting tool will flag the parts of your code that look wrong or inconsistent with PEP 8. You can then make fixes manually. There are different linters for Python, like pylint or Flake8, that you can integrate into your editor. If you are using an IDE like Pycharm, it will come with a preinstalled linter.
Auto-formatters like Black are more aggressive than linters, in that they do not flag your errors or inconsistencies, but they actually go in and modify your code to comply with PEP 8.
However, since the very first guideline plainly instructs the use of common sense, the net value of an automatic tool to clean your code and make it beautiful is up for debate. Many automated rules can’t account for the context where they are being used, and thus their changes might contradict common sense. As this blog post states: “Autoformatters [..] are soulless.”
Pro Tips for Pythonic Style
So how do you become a writer of Pythonic code? Here are our top three tips to get there:
- Read code. Yours and others.’ You may find that you’re not able to understand something you wrote three months ago. And you might discover code written by other people that is at once intuitively understandable. All this will help you arrive at your own definition of “readability” and how to get there.
- Read the style guides, particularly PEP 8. As we discussed, you don’t always need to stick to the rules 100%. But in order to do that, you need to know the rules! So if someone calls you out for not complying with PEP 8, you can tell them why you chose to do it that way — or admit that they’re right, thank them and change your code accordingly (mistakes help you grow).
- Use a linter. The beneficial side-effect of linters is that they teach you the standards. Even seasoned Python programmers appreciate these simple tools for their utility.
Are you looking to become a true Pythoneer? Enroll now in our Nanodegree.