0% found this document useful (0 votes)
67 views5 pages

Pythonic Coding Practices Guide

The document discusses the concept of 'Pythonic' code, emphasizing the importance of following the idioms and style preferred by the Python community for readability and simplicity. It highlights the significance of using Python 3 and adhering to the PEP 8 style guide for formatting code, including guidelines on whitespace, naming conventions, expressions, and import statements. Additionally, it introduces the tool 'black' for automatic PEP 8 formatting to help maintain consistent coding styles.

Uploaded by

Jordan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views5 pages

Pythonic Coding Practices Guide

The document discusses the concept of 'Pythonic' code, emphasizing the importance of following the idioms and style preferred by the Python community for readability and simplicity. It highlights the significance of using Python 3 and adhering to the PEP 8 style guide for formatting code, including guidelines on whitespace, naming conventions, expressions, and import statements. Additionally, it introduces the tool 'black' for automatic PEP 8 formatting to help maintain consistent coding styles.

Uploaded by

Jordan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1 Pythonic Thinking

The idioms of a programming language are defined by its users.


Over the years, the Python community has come to use the adjective
Pythonic to describe code that follows a particular style. The Pythonic
style isn’t regimented or enforced by the compiler. It has emerged over
time through experience using the language and working with oth-
ers. Python programmers prefer to be explicit, to choose simple over
complex, and to maximize readability. (Type import this into your
interpreter to read The Zen of Python.)
Programmers familiar with other languages may try to write Python
as if it’s C++, Java, or whatever they know best. New programmers
may still be getting comfortable with the vast range of concepts that
can be expressed in Python. It’s important for you to know the best—
the Pythonic—way to do the most common things in Python. These
patterns will affect every program you write.

Item 1: Know Which Version of Python You’re Using


Throughout this book, the majority of example code is for Python 3.13
(released in October 2024). This book does not cover Python 2,
although it sometimes mentions older versions of Python 3 to provide
background information about how the language has evolved over
time.
Many computer operating systems ship with multiple versions of
the standard CPython interpreter preinstalled. However, the default
meaning of python on the command line may not be clear. python is
usually an alias for python2.7, but it can sometimes be an alias for
even older versions, like python2.6 or python2.5. To find out exactly
which version of Python you’re using, you can use the --version flag:
$ python --version
Python 2.7.10

Humble Bundle Pearson Python Bundle Ð © Pearson. Do Not Distribute.


2 Chapter 1 Pythonic Thinking

On many systems, Python 2 is no longer installed, and the python


command causes an error:
$ python --version
-bash: python: command not found

Python 3 is usually available under the name python3:


$ python3 --version
Python 3.12.3

To use alternative Python runtimes, such as PyPy (https://


[Link]), to run Python programs, you need to use their
specific commands:
$ pypy3 --version
Python 3.10.14 (75b3de9d9035, May 28 2024, 18:06:40)
[PyPy 7.3.16 with GCC Apple LLVM 15.0.0 (clang-1500.3.9.4)]

You can also figure out the version of Python you’re using at runtime
by inspecting values in the sys built-in module:
import sys

print([Link])
print([Link])
print(sys.version_info)
print([Link])
>>>
darwin
cpython
sys.version_info(major=3, minor=12, micro=3,
�releaselevel='final', serial=0)
3.12.3 (main, Apr 9 2024, 08:09:14)
�[Clang 15.0.0 (clang-1500.3.9.4)]

For a long time, the Python core developers and community were
actively maintaining support for both Python 2 and Python 3. The
versions are different in significant ways and have incompatibilities
that made porting difficult. The migration from version 2 to version 3
was an extremely long and painful period that finally came to an
end on April 20, 2020, when Python version 2.7.18 was published.
This was the final official release of Python 2. For anyone who still
needs security patches and bug fixes for Python 2, the only remain-
ing options are to pay a commercial software vendor for support or do
it yourself.
Since then, the Python core developers and community have been
focused on Python version 3. The functionality of the core language,

Humble Bundle Pearson Python Bundle Ð © Pearson. Do Not Distribute.


Item 2: Follow the PEP 8 Style Guide 3

the standard library, and the ecosystem of packages and tools are
constantly being improved. Keeping up with all the changes and
innovations that are happening can be overwhelming. One good way
to find out about what’s new is to read the release notes (https://
[Link]/3/whatsnew/[Link]), which highlight additions
and changes for each version. There are other websites out there
that will also notify you when the community packages you rely on
are updated (see Item 116: “Know Where to Find Community-Built
Modules”).

Things to Remember
✦ Python 3 is the most up-to-date and well-supported version of
Python, and you should use it for your projects.
✦ Be sure that the command-line executable for running Python on
your system is the version you expect it to be.
✦ Python 2 is no longer officially maintained by the core developers.

Item 2: Follow the PEP 8 Style Guide


Python Enhancement Proposal #8, otherwise known as PEP 8, is the
style guide for how to format Python code. You are welcome to write
Python code any way you want, as long as it has valid syntax. How-
ever, using a consistent style makes your code more approachable
and easier to read. Sharing a common style with other Python pro-
grammers in the larger community facilitates collaboration on proj-
ects. But even if you are the only one who will ever read your code,
following the style guide will make it easier for you to change things
later and can help you avoid many common errors.
PEP 8 provides a wealth of details about how to write clear Python
code. It continues to be updated as the Python language evolves. It’s
worth reading the whole guide online ([Link]
peps/pep-0008/). Here are a few rules you should be sure to follow.

Whitespace
In Python, whitespace is syntactically significant. Python program-
mers are especially sensitive to the effects of whitespace on code clar-
ity. Follow these guidelines related to whitespace:
■ Use spaces instead of tabs for indentation.
■ Use four spaces for each level of syntactically significant indenting.
■ Lines should be 79 characters in length or less.

Humble Bundle Pearson Python Bundle Ð © Pearson. Do Not Distribute.


4 Chapter 1 Pythonic Thinking

■ Continuations of long expressions onto additional lines should be


indented by four extra spaces from their normal indentation level.
■ In a file, functions and classes should be separated by two blank
lines.
■ In a class, methods should be separated by one blank line.
■ In a dictionary, put no whitespace between each key and colon;
put a single space before the corresponding value if it fits on the
same line.
■ Put one—and only one—space before and after the = operator in a
variable assignment.
■ For type annotations, ensure that there is no separation between
the variable name and the colon, and use a space before the type
information.

Naming
PEP 8 suggests unique styles of naming for different parts in the lan-
guage. These conventions make it easy to distinguish which type cor-
responds to each name when reading code. Follow these guidelines
related to naming:
■ Functions, variables, and attributes should be in
lowercase_underscore format.
■ Protected instance attributes should be in _leading_underscore
format.
■ Private instance attributes should be in __double_leading_
underscore format.
■ Classes (including exceptions) should be in CapitalizedWord format.
■ Module-level constants should be in ALL_CAPS format.
■ Instance methods in classes should use self, which refers to the
object, as the name of the first parameter.
■ Class methods should use cls, which refers to the class, as the
name of the first parameter.

Expressions and Statements


The Zen of Python states: “There should be one—and preferably only
one—obvious way to do it.” PEP 8 attempts to codify this style in its
guidance for expressions and statements:
■ Use inline negation (if a is not b) instead of negation of positive
expressions (if not a is b).

Humble Bundle Pearson Python Bundle Ð © Pearson. Do Not Distribute.


Item 2: Follow the PEP 8 Style Guide 5

■ Don’t check for empty containers or sequences (like [] or "") by com-


paring the length to zero (if len(somelist) == 0). Use if not somelist
and assume that empty values will implicitly evaluate to False.
■ The same thing goes for non-empty containers or sequences (like
[1] or "hi"). The statement if somelist is implicitly True for non-
empty values.
■ Avoid single-line if statements, for and while loops, and except
compound statements. Spread these over multiple lines for clarity.
■ If you can’t fit an expression on one line, surround it with paren-
theses and add line breaks and indentation to make it easier to
read.
■ Prefer surrounding multiline expressions with parentheses over
using the \ line continuation character.

Imports
PEP 8 suggests some guidelines for how to import modules and use
them in your code:
■ Always put import statements (including from x import y) at the
top of a file.
■ Always use absolute names for modules when importing them,
not names relative to the current module’s own path. For exam-
ple, to import the foo module from within the bar package, you
should use from bar import foo, not just import foo.
■ If you must do relative imports, use the explicit syntax from .
import foo.
■ Imports should be in sections in the following order: standard
library modules, third-party modules, your own modules. Each
subsection should have imports in alphabetical order.

Automation
If what you’ve read so far seems like a lot to remember, I have good
news: The Python community is coalescing around a common tool
for automatic PEP 8 formatting: It’s called black ([Link]
psf/black), and it’s an official Python Software Foundation project.
black provides very few configuration options, which makes it easy
for developers working on the same codebase to agree on the style of
code. Installing and using black is straightforward:
$ pip install black
$ python -m black [Link]
reformatted [Link]

Humble Bundle Pearson Python Bundle Ð © Pearson. Do Not Distribute.

You might also like