Python Project – Build A Package

Goal

Build a Python package from source code.

Requirements

  1. You've gone through Create A Package
  2. Install setuptools and wheel
    $ pip install -U setuptools wheel
  3. (Optional) Use this project as a template if you haven't previously created a Python project

Build A Package

Once your project is ready to be built, execute the following command.

$ python setup.py sdist bdist_wheel
  • sdist: you're creating setuptools artifacts - enable installing from source code
  • bdist_wheel: you're creating a wheel artifact - a single .whl file which is like a ZIP file of the whole package
  • Why sdist?: If the installation from wheel fails, for any reason, then pip falls back and installs from source code (setuptools)

Build Artifacts

The following directories will be created after the Build step.

  1. .eggs: Contains eggs that were downloaded by setuptools to build, test, and run plug-ins
  2. build: Source files of the package that will be zipped into .whl; this is a temporary folder, and it can be ignored
  3. {APP_NAME}.egg-info: The package's metadata, such as the path to app source files, required packages, entrypoint (for Python CLI App), etc.
  4. dist: Artifacts that can be used by pip to install the Python app. The wheel file name is dependant on the wheel's type. If you didn't specify anything, you'd probably generate this filename {APP_NAME}-{APP_VERSION}-py3-none-any.whl

Install A Wheel Package

The following Bash script will search for *.whl in dist/; there should be only one file. If you're building for a specific operating system, like macOS, Windows, or Linux, then change *.whl to *{SPECIFIC_OS_NAME}*.whl.

The {} represents the name of the *.whl file that was found, and \; means it's the end of an -exec.

$ find dist/ -type f -name *.whl -exec pip install {} \;

This step is useful for checking whether the wheel package was built properly before publishing it to PyPi.

References


This blog post is part of the Python Project series, and is based on this GitHub repository - unfor19/python-project.
The GitHub repo includes an example of a Python project, and Wiki Pages that describe the necessary steps for developing, creating and distributing a Python package.


Originally published at github.com/unfor19/python-project on 8 November, 2020