python-blueprint
Example Python project that demonstrates how to create a tested Python package using the latest
Python testing and linting tooling. The project contains a fact
package that provides a
simple implementation of the factorial algorithm
(fact.lib
) and a command line interface (fact.cli
).
Requirements
Python 3.5+.
Note
Because Python 2.7 supports ends January 1, 2020, new projects should consider supporting Python 3 only, which is simpler than trying to support both. As a result, support for Python 2.7 in this example project has been dropped.
Windows Support
Summary: On Windows, use py
instead of python3
for many of the examples in this
documentation.
This package fully supports Windows, along with Linux and macOS, but Python is typically
installed differently on Windows.
Windows users typically access Python through the
py launcher rather than a python3
link in their PATH
. Within a virtual environment, all platforms operate the same and use a
python
link to access the Python version used in that virtual environment.
Packaging
This project is designed as a Python package, meaning that it can be bundled up and redistributed as a single compressed file.
Packaging is configured by:
setup.py
setup.cfg
MANIFEST.in
To package the project as a source distribution:
$ python3 setup.py sdist
This will generate dist/fact-1.0.0.tar.gz
. This redistributable package can be
uploaded to PyPI or installed
directly from the filesystem using pip
.
It is normally most convenient to build a Python application as a binary wheel for distribution. Read more about the advantages of wheels.
To create a wheel:
$ python3 -m pip install wheel
$ python3 setup.py bdist_wheel
This will generate dist/fact-1.0.0-py3-none-any.whl
, which can be distributed and
installed. Unlike source distributions, users will not have to execute a setup.py
in order to
install the wheel.
Testing
Automated testing is performed using tox.
tox will automatically create virtual environments based on tox.ini
for unit testing,
PEP8 style guide checking, and documentation generation.
# Install tox (only needed once).
$ python3 -m pip install tox
# Run all environments.
# To only run a single environment, specify it like: -e pep8
$ tox
Unit Testing
Unit testing is performed with pytest. pytest has become the defacto Python unit testing framework. Some key advantages over the built in unittest module are:
- Significantly less boilerplate needed for tests.
- PEP8 compliant names (e.g.
pytest.raises()
instead ofself.assertRaises()
). - Vibrant ecosystem of plugins.
pytest will automatically discover and run tests by recursively searching for folders and .py
files prefixed with test
for any functions prefixed by test
.
The tests
folder is created as a Python package (i.e. there is an __init__.py
file
within it) because this helps pytest
uniquely namespace the test files. Without this,
two test files cannot be named the same, even if they are in different sub-directories.
Code coverage is provided by the pytest-cov plugin.
When running a unit test tox environment (e.g. tox
, tox -e py37
, etc.), a data file
(e.g. .coverage.py37
) containing the coverage data is generated. This file is not readable on
its own, but when the coverage
tox environment is run (e.g. tox
or tox -e -coverage
),
coverage from all unit test environments is combined into a single data file and an HTML report is
generated in the htmlcov
folder showing each source file and which lines were executed during
unit testing is generated in Open htmlcov/index.html
in a web browser to view the report. Code
coverage reports help identify areas of the project that are currently not tested.
Code coverage is configured in the .coveragerc
file.
Code Style Checking
PEP8 is the universally accepted style
guide for Python code. PEP8 code compliance is verified using flake8.
flake8 is configured in the [flake8]
section of tox.ini
. Three extra flake8 plugins
are also included:
pep8-naming
: Ensure functions, classes, and variables are named with correct casing.flake8-quotes
: Ensure that' '
style string quoting is used consistently.flake8-import-order
: Ensure consistency in the way imports are grouped and sorted.
Generated Documentation
Documentation that includes the README.rst
and the Python project modules is automatically
generated using a Sphinx tox environment. Sphinx is a documentation
generation tool that is the defacto tool for Python documentation. Sphinx uses the
RST markup language.
This project uses the napoleon plugin for Sphinx, which renders Google-style docstrings. Google-style docstrings provide a good mix of easy-to-read docstrings in code as well as nicely-rendered output.
"""Computes the factorial through a recursive algorithm.
Args:
n: A positive input value.
Raises:
InvalidFactorialError: If n is less than 0.
Returns:
Computed factorial.
"""
The Sphinx project is configured in docs/conf.py
.
Build the docs using the docs
tox environment (e.g. tox
or tox -e docs
). Once built,
open docs/_build/index.html
in a web browser.
Generate a New Sphinx Project
To generate the Sphinx project shown in this project:
$ mkdir docs
$ cd docs
$ sphinx-quickstart --no-makefile --no-batchfile --extensions sphinx.ext.napoleon
# When prompted, select all defaults.
Modify conf.py
appropriately:
# Add the project's Python package to the path so that autodoc can find it.
import os
import sys
sys.path.insert(0, os.path.abspath('../src'))
...
html_theme_options = {
# Override the default alabaster line wrap, which wraps tightly at 940px.
'page_width': 'auto',
}
Modify index.rst
appropriately:
.. include:: ../README.rst apidoc/modules.rst
Project Structure
Traditionally, Python projects place the source for their packages in the root of the project structure, like:
fact ├── fact │ ├── __init__.py │ ├── cli.py │ └── lib.py ├── tests │ ├── __init__.py │ └── test_fact.py ├── tox.ini └── setup.py
However, this structure is known to have bad
interactions with pytest
and tox
, two standard tools maintaining Python projects. The
fundamental issue is that tox creates an isolated virtual environment for testing. By installing
the distribution into the virtual environment, tox
ensures that the tests pass even after the
distribution has been packaged and installed, thereby catching any errors in packaging and
installation scripts, which are common. Having the Python packages in the project root subverts
this isolation for two reasons:
- Calling
python
in the project root (for example,python -m pytest tests/
) causes Python to add the current working directory (the project root) tosys.path
, which Python uses to find modules. Because the source packagefact
is in the project root, it shadows thefact
package installed in the tox environment. - Calling
pytest
directly anywhere that it can find the tests will also add the project root tosys.path
if thetests
folder is a a Python package (that is, it contains a__init__.py
file). pytest adds all folders containing packages tosys.path
because it imports the tests like regular Python modules.
In order to properly test the project, the source packages must not be on the Python path. To prevent this, there are three possible solutions:
- Remove the
__init__.py
file fromtests
and runpytest
directly as a tox command. - Remove the
__init__.py
file from tests and change the working directory ofpython -m pytest
totests
. - Move the source packages to a dedicated
src
folder.
The dedicated src
directory is the recommended solution
by pytest
when using tox and the solution this blueprint promotes because it is the least
brittle even though it deviates from the traditional Python project structure. It results is a
directory structure like:
fact ├── src │ └── fact │ ├── __init__.py │ ├── cli.py │ └── lib.py ├── tests │ ├── __init__.py │ └── test_fact.py ├── tox.ini └── setup.py
Type Hinting
Type hinting allows developers to include optional static typing information to Python source code. This allows static analyzers such as PyCharm, mypy, or pytype to check that functions are used with the correct types before runtime.
For PyCharm in particular, the IDE is able to provide much richer auto-completion, refactoring, and type checking while the user types, resulting in increased productivity and correctness.
This project uses the type hinting syntax introduced in Python 3:
def factorial(n: int) -> int:
Type checking is performed by mypy via tox -e mypy
. mypy is configured in setup.cfg
.
PyCharm Configuration
To configure PyCharm 2018.3 and newer to align to the code style used in this project:
Settings | Search "Hard wrap at"
- Editor | Code Style | General | Hard wrap at: 99
Settings | Search "Optimize Imports"
Editor | Code Style | Python | Imports
- Check: Sort import statements
- Check: Sort imported names in "from" imports
- Uncheck: Sort plain and "from" imports separately within a group
- Check: Sort case-insensitively
Settings | Search "Docstrings"
- Tools | Python Integrated Tools | Docstrings | Docstring Format: Google
(Optional) Settings | Search "Force parentheses"
- Editor | Code Style | Python | Wrapping and Braces | "From Import Statements: Check Force parentheses if multiline