3 The Zen of Python
PEP 20 – The Zen of Python contains the defining principles of Python’s design. Don’t worry if it doesn’t make complete sense yet! It is part style guide, part community in-joke, and part tiny philosophical compass.
>>> import this
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!Style Guide for Python Code
Alongside PEP 20, there’s PEP 8, the de facto style guide for Python developers. The Python community often tries to follow these guidelines. They’re not laws, but they do help make your code more consistent and easier for other Python developers to debug or contribute to.
There are some good reasons to ignore guidelines, too. PEP 8 gives examples like these:
When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
To be consistent with surrounding code that also breaks it (maybe for historic reasons).
Because the code in question predates the guideline and there’s no other reason to be modifying it.
When the code needs to remain compatible with older versions of Python that don’t support the feature recommended by the style guide.
pep8.org exists as a more digestible version of the guideline. Read style advice as a way to make code kinder to the next person, not as a tiny judge in a robe.
Conventions
The examples in this section use the same basic convention: show a common first attempt, then show the clearer Python style. Okay means the code may work, but it asks the reader to do more mental bookkeeping. Better means the same idea expressed in the style Python programmers usually reach for.
Checking Objects
If you don’t need to explicitly check whether a value is True, False, None, or 0, you can usually put it straight into the if statement.
This is one of those things that feels suspiciously casual the first time you see it. Python is doing a truth-value test for you, which is a short way of asking “does this object count as something here?”
Okay
>>> if value == True:
... print("True")
True
>>> if value == None:
... print("Value is None")
Value is NoneBetter
>>> if value:
... print("Value is Truthy")
Value is Truthy
>>> if not value:
... print("Value is Falsy")
Value is Falsy
>>> if value is None:
... print("Value is None")
Value is NoneReading from a File
When reading a file, pathlib.Path gives the filename useful methods instead of leaving it as a plain string. For small text files, read_text() is tidy. For wordlists, logs, and other files you may want to process one line at a time, open the file from the Path object with a context manager.
The most important part of this example is using a context manager when dealing with file objects. It closes the file properly even if your code hits an exception, which is one less issue for you to deal with later.
Okay
>>> from pathlib import Path
>>> path = Path("file.txt")
>>> contents = path.read_text(encoding="utf-8")
>>> print(contents)Better
>>> from pathlib import Path
>>> path = Path("file.txt")
>>> with path.open(encoding="utf-8") as file:
... for line in file:
... print(line.rstrip())More on Truth Value Testing
Most objects in Python can be tested for truth value. By default, an object counts as True unless its class defines a boolean method, or it has a length method that returns zero.
The most common built-in objects considered False are:
- constants defined as
FalseorNone - zero of any numeric type
0,0.0 - empty sequences and collections
'',(),[],{},set(),range()
This is why an empty list can be used directly in an if statement, and it’s also why value is None isn’t the same as not value: 0, "", and [] are all falsey, but none of them are the special None value.
Checkpoint
Rewrite one explicit truth check from your own code, or from the examples above, so it uses Python truth-value testing. Then explain why value is None is still different from not value; if you can explain the difference out loud, you’re doing more than just copying the prettier version.
Extension Activity
Read Python’s documentation on truth value testing, pathlib, and text file I/O. Add one more Okay / Better pair that compares a less direct approach with a clearer Python pattern.