Building Python Packages Using Setuptools

In this blog, we are going to create a source distribution and wheels of python package using Setuptools.  Before moving towards how we can package. Let’s first understand what source distribution and wheel file are.

Package means a usable unit or library which can be provided to solve a particular use case. For packaging, we have different build tools like in Scala we have SBT or In JAVA we have maven etc. Similarly, we have Setuptools in python to create a distribution. Source Distribution (sdist) and Wheels (whl) are the two main ways of creating a package distribution in python.

Source Distribution ( sdist ):  Apart from source code It contains extra files like CI scripts, test cases etc ) which do not require to be present for the end user and least used approach.  This will distribute the package in form creates the archive in a different format for the different platform. The default format is a gzipped tar file (.tar.gz) on Linux and ZIP file on Windows.

Wheels (whl) : This distribution contains source files and package metadata which will be required for installing. (.whl)

setup.py :

  1. This file contains setup() function in which we provide specific details of your project. This contains information like package name, version, require packages, author, description, classifier etc.
  2. It’s the command line interface for running various commands that relate to packaging tasks. If you want to more digging into just run python setup.py –helpImage result for python packaging

For the project structure, I am using the following structure:

dummy_project/
|-- README
|-- setup.py
|-- example_pkg
|   |-- __init__.py
|   |-- calculate.py
|   |-- result.py
|-- tests
|-- |-- __init__.py
|-- |-- run.py
|-- |-- test.py

Let’s create the most important file setup.py which exists at the root of your project directory.

from setuptools import setup

setup(
    name = "dummy_project",
    version = "1.0.0",
    author = "dummy",
    author_email = "dummy@domain.com",
    description = ("This project helps to understand about setup.py."),
    url = "https://www.python.org/doc/",
    packages=['example_pkg'],
    python_requires='>=3.6.0'
)

Now, let’s Creates a distribution using the following command

python setup.py sdist bdist_wheel

This will generate both distributions. Now depending upon your use case you can push your package to the public or private python repo. That can be installed via pip command like this:

pip install package_name

In the next blog, we will learn how we can perform automated versioning of python project.

References:
https://packaging.python.org/


Knoldus-blog-footer-image

Leave a Reply

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!