The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
19 Aesthetic Python Code
Python is known for its readability and clean syntax. Writing aesthetically pleasing code is not just about following the rules of the language; it’s also about adhering to best practices and conventions that make your code more readable and maintainable. In this section, we will discuss some general principles and guidelines for writing aesthetic Python code.
19.1 Why Aesthetics Matter
Aesthetic code is not just about making your code look pretty; it’s about making it easier to read, understand, and maintain. Here are some reasons why aesthetics matter in programming:
- Readability: Aesthetic code is easier to read and understand, reducing the cognitive load on developers.
- Maintainability: Well-formatted code is easier to maintain and update, saving time and effort in the long run.
- Collaboration: Aesthetic code is easier for other developers to work with, facilitating collaboration and code reviews.
- Debugging: Clean code makes it easier to identify and fix bugs, improving the overall quality of the codebase.
- Consistency: Following a consistent style guide makes the codebase more uniform and predictable.
- Professionalism: Aesthetic code reflects professionalism and attention to detail, which is important in software development.
19.2 The Zen of Python
The Zen of Python is a collection of 19 guiding principles for writing computer programs in Python. These principles were written by Tim Peters and are included in the Python interpreter as an Easter egg. You can view the Zen of Python by running import this
in a Python interpreter (see Listing 19.1).
You will become familiar with the terms and concepts in the Zen of Python as you gain more experience with Python programming. Following these principles can help you write more aesthetic and Pythonic code.
19.3 How Many Characters Per Line?
One of the most debated topics in Python coding style is the maximum number of characters per line. While Python does not enforce a strict limit on line length, the Python community generally follows the 79-character limit recommended by PEP 8, the official Python style guide.
The 79-character limit is based on historical reasons related to the width of terminals and code review tools. It is also considered a good compromise between readability and the ability to have multiple code panes open side by side.
However, some developers prefer a 100-character limit, which allows for more content on a single line without sacrificing readability. Ultimately, the choice of line length limit depends on the project’s requirements and the team’s preferences. In Listing 19.2, we provide an example of how to wrap long lines in Python code.
# PEP 8 recommends a maximum 79-character limit, which ends here ------------->
# Longer lines should be wrapped to the next line using parentheses
# or backslashes for readability.
def calculate_total(
price: float,
quantity: int,
discount: float,
) -> float:
return (price * quantity) * (1 - discount)
19.4 Indentation and Whitespace
Indentation and whitespace play a crucial role in Python code aesthetics. Python uses indentation to define code blocks, such as loops, conditionals, and functions. Consistent indentation makes the code more readable and helps developers understand the structure of the code.
Here are some guidelines for indentation and whitespace in Python:
- Use 4 spaces for indentation (not tabs) to conform to PEP 8. Most code editors can be configured to insert spaces when you press the Tab key (this is already the default in many editors).
- Avoid mixing tabs and spaces for indentation. Choose one and stick with it.
- Use a single space after commas in function arguments and between operators for readability. For example,
x = 5 + 3
, notx=5+3
. - Use blank lines to separate logical sections of code and improve readability. For example, separate functions, classes, and blocks of code with blank lines.
- Avoid excessive whitespace at the end of lines or in empty lines. Most code editors can remove trailing whitespace automatically.
- Use vertical alignment sparingly to improve readability. For example, aligning variable assignments or dictionary keys can make the code more aesthetically pleasing.
19.5 Automated Code Formatting
To ensure consistent code style and formatting across a project, you can use automated code formatting tools like black
, autopep8
, or yapf
. These tools automatically format your code according to a predefined style guide, such as PEP 8, and can be integrated into your development workflow.
For example, black
is a popular code formatter that reformats your code in place to adhere to the black code style. You can install black
using pip
and run it on your Python files to automatically format them. In Listing 19.3, we provide an example of using black
to format a Python file.
black
to format a Python file according to the black code style. The --line-length
option specifies the maximum line length.
Automated code formatting tools can save time and effort by enforcing code style consistency and reducing the need for manual formatting. They can also help prevent style-related issues during code reviews and improve the overall quality of the codebase.
19.6 Docstrings and Comments
Docstrings and comments are essential for documenting code and providing explanations for developers. They help clarify the purpose of functions, classes, and modules, making it easier to understand and maintain the codebase.
Here are some guidelines for writing docstrings and comments in Python:
- Use docstrings to describe the purpose, parameters, and return values of functions and classes. Docstrings should be enclosed in triple quotes (
"""
) and preferably follow a consistent format like Google Style Docstrings or NumPy Docstring Standard. - Use comments to explain complex or non-obvious parts of the code. Comments should be concise, clear, and relevant to the code they describe.
19.7 Will Aesthetics Matter in the Future, as AI Takes Over?
In the age of artificial intelligence and machine learning, where natural language processing models can generate code and algorithms, the question arises: Does aesthetics still matter in programming? Maybe no. Machines could start generating code that is optimized for execution and performance, but not necessarily aesthetically pleasing to humans. After all, the goal of code is to be executed by machines, not to be admired by humans.
In the meantime, as long as humans are writing and reading code, aesthetics will continue to play a crucial role in software development. Aesthetic code is not just about beauty; it’s about clarity, maintainability, and collaboration. By following best practices and conventions, you can write code that is not only functional but also elegant and easy to work with.